@vincentbanana/banana-gui 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ui/app.js CHANGED
@@ -31,6 +31,16 @@ const ICONS = {
31
31
  sun: '<circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4"/>',
32
32
  moon: '<path d="M20 14.5A8 8 0 019.5 4a8 8 0 1010.5 10.5z"/>',
33
33
  contrast: '<circle cx="12" cy="12" r="8"/><path d="M12 4v16"/><path d="M12 4a8 8 0 010 16" fill="currentColor" stroke="none"/>',
34
+ plug: '<path d="M9 3v5M15 3v5M7 8h10v3a5 5 0 0 1-10 0zM12 16v5"/>',
35
+ command: '<path d="M9 6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3z"/>',
36
+ wrap: '<path d="M4 6h16M4 12h12a3 3 0 1 1 0 6h-3M4 18h4"/>',
37
+ expand: '<path d="M9 4H4v5M15 4h5v5M9 20H4v-5M15 20h5v-5"/>',
38
+ copy: '<rect x="8" y="8" width="11" height="11" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/>',
39
+ info: '<circle cx="12" cy="12" r="8"/><path d="M12 11v5M12 8h.01"/>',
40
+ minimize: '<path d="M5 12h14"/>',
41
+ maximize: '<rect x="6" y="6" width="12" height="12" rx="1"/>',
42
+ restore: '<rect x="5" y="8" width="9" height="9" rx="1"/><path d="M9 5h9v9"/>',
43
+ diff: '<path d="M6 4v16M18 4v16M3 8h6M15 16h6M3 16h6M15 8h6"/>',
34
44
  };
35
45
 
36
46
  const TOOL_ICON = {
@@ -152,7 +162,23 @@ function highlightPreview(element, path, code) {
152
162
 
153
163
 
154
164
  // ---------------- 状态 ----------------
155
- const state = { info: null, sessions: [], attachments: [], busy: false, pendingApproval: null };
165
+ const state = {
166
+ info: null,
167
+ sessions: [],
168
+ attachments: [],
169
+ busy: false,
170
+ pendingApproval: null,
171
+ settingsCategory: 'model',
172
+ settingsScroll: 0,
173
+ plugins: null,
174
+ preview: null,
175
+ overlay: null,
176
+ ccIndex: 0,
177
+ ccItems: [],
178
+ workbench: { open: false, tab: 'terminal', width: 420 },
179
+ changes: null,
180
+ changesFile: null,
181
+ };
156
182
 
157
183
  const THREAD = $('thread');
158
184
 
@@ -205,10 +231,12 @@ async function switchSession(ref) {
205
231
  const result = await post('session', { action: 'switch', ref });
206
232
  if (result?.info) state.info = result.info;
207
233
  if (result?.sessions) state.sessions = result.sessions;
234
+ state.changes = null;
208
235
  renderHeader();
209
236
  renderSidebar();
210
237
  renderThread();
211
238
  $('filesTitle').textContent = `项目文件 · ${state.info?.workspace ?? ''}`;
239
+ if (state.workbench.open && state.workbench.tab === 'changes') void loadChanges(true);
212
240
  closeSidebarIfOverlay();
213
241
  } catch (error) {
214
242
  toast('切换会话失败:' + (error?.message ?? error));
@@ -338,8 +366,17 @@ function downloadSession(format, id) {
338
366
  }
339
367
 
340
368
  function toolGroup(calls, results) {
341
- const wrap = document.createElement('div');
342
- wrap.className = 'tool-group';
369
+ const wrap = document.createElement('details');
370
+ wrap.className = 'work-group';
371
+ const hasError = calls.some((call) => results.get(call.id)?.isError);
372
+ wrap.open = hasError;
373
+ wrap.classList.toggle('has-error', hasError);
374
+ const summary = document.createElement('summary');
375
+ summary.innerHTML =
376
+ `<span class="wg-dot"></span><span class="wg-title">运行了 ${calls.length} 个工具</span>` +
377
+ `<span class="wg-state">${hasError ? '有失败' : ''}</span>`;
378
+ const body = document.createElement('div');
379
+ body.className = 'tool-group-body';
343
380
  for (const call of calls) {
344
381
  const result = results.get(call.id);
345
382
  const row = document.createElement('div');
@@ -350,8 +387,14 @@ function toolGroup(calls, results) {
350
387
  `<span class="t-name">${escapeHtml(call.name)}</span>` +
351
388
  `<span class="t-detail">${escapeHtml(detail)}</span>` +
352
389
  `<span class="t-state">${result ? (result.isError ? '失败' : escapeHtml(result.content?.slice(0, 40) ?? '完成')) : '已调用'}</span>`;
353
- wrap.appendChild(row);
390
+ if (result?.content) {
391
+ row.classList.add('is-clickable');
392
+ row.title = '点击展开输出';
393
+ row.addEventListener('click', () => toggleToolOutput(row, result.content, Boolean(result.isError)));
394
+ }
395
+ body.appendChild(row);
354
396
  }
397
+ wrap.append(summary, body);
355
398
  return wrap;
356
399
  }
357
400
 
@@ -510,6 +553,130 @@ async function refreshSettings() {
510
553
  if (!$('settingsSheet').hidden) renderSettings();
511
554
  }
512
555
 
556
+ // ---------------- 覆盖层与通用交互 ----------------
557
+ const sleep = (ms) => new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
558
+
559
+ function hideAnimated(element, className = 'is-closing', ms = 180) {
560
+ if (!element || element.hidden) return Promise.resolve();
561
+ element.classList.add(className);
562
+ return sleep(ms).then(() => {
563
+ // 动画期间如果又被打开,就不要把面板藏起来
564
+ if (!element.classList.contains(className)) return;
565
+ element.hidden = true;
566
+ element.classList.remove(className);
567
+ });
568
+ }
569
+
570
+ function syncOverlayState() {
571
+ const open =
572
+ !$('commandCenter').hidden ||
573
+ !$('codeViewer').hidden ||
574
+ !$('settingsSheet').hidden ||
575
+ !$('workbench').hidden ||
576
+ !$('approvalModal').hidden;
577
+ document.body.classList.toggle('has-overlay', open);
578
+ }
579
+
580
+ function closeTopOverlay() {
581
+ if (!$('selectionTools').hidden) return hideSelectionTools();
582
+ if (!$('commandCenter').hidden) return closeCommandCenter();
583
+ if (!$('codeViewer').hidden) return closeViewer();
584
+ if (!$('settingsSheet').hidden) return closeSettings();
585
+ if (!$('approvalModal').hidden) return closeApproval(false);
586
+ if (!$('workbench').hidden) return closeWorkbench();
587
+ return false;
588
+ }
589
+
590
+ async function copyText(text, message = '已复制') {
591
+ try {
592
+ await navigator.clipboard.writeText(text);
593
+ } catch {
594
+ const area = document.createElement('textarea');
595
+ area.value = text;
596
+ area.style.cssText = 'position:fixed;left:-9999px;top:0';
597
+ document.body.appendChild(area);
598
+ area.select();
599
+ document.execCommand('copy');
600
+ area.remove();
601
+ }
602
+ toast(message);
603
+ }
604
+
605
+ function insertComposer(text) {
606
+ const input = $('input');
607
+ input.value = text;
608
+ grow();
609
+ input.focus();
610
+ input.setSelectionRange(input.value.length, input.value.length);
611
+ }
612
+
613
+ function askAboutText(text, path, kind = 'code') {
614
+ const trimmed = text.trim();
615
+ if (!trimmed) return;
616
+ const clipped = trimmed.length > 12_000 ? `${trimmed.slice(0, 12_000)}\n…(已截断)` : trimmed;
617
+ const body =
618
+ kind === 'terminal'
619
+ ? `这段终端输出看起来有问题,帮我分析原因,并给出可以直接执行的修复步骤:\n\n\`\`\`\n${clipped}\n\`\`\``
620
+ : `请解释并检查这段代码${path ? `(${path})` : ''},指出潜在问题,必要时给出修改方案:\n\n\`\`\`\n${clipped}\n\`\`\``;
621
+ insertComposer(body);
622
+ toast(kind === 'terminal' ? '已带入终端输出,回车发送' : '已带入选中代码,回车发送');
623
+ hideSelectionTools();
624
+ }
625
+
626
+ function hideSelectionTools() {
627
+ const box = $('selectionTools');
628
+ box.hidden = true;
629
+ box.innerHTML = '';
630
+ syncOverlayState();
631
+ }
632
+
633
+ function showSelectionTools(x, y, buttons) {
634
+ const box = $('selectionTools');
635
+ box.innerHTML = '';
636
+ for (const item of buttons) {
637
+ const button = document.createElement('button');
638
+ button.textContent = item.label;
639
+ button.addEventListener('mousedown', (event) => event.preventDefault());
640
+ button.addEventListener('click', item.run);
641
+ box.appendChild(button);
642
+ }
643
+ box.hidden = false;
644
+ box.style.visibility = 'hidden';
645
+ box.style.left = '0px';
646
+ box.style.top = '0px';
647
+ const width = box.offsetWidth;
648
+ const height = box.offsetHeight;
649
+ box.style.left = `${Math.max(8, Math.min(x - width / 2, window.innerWidth - width - 8))}px`;
650
+ box.style.top = `${Math.max(8, Math.min(y - height - 10, window.innerHeight - height - 8))}px`;
651
+ box.style.visibility = '';
652
+ syncOverlayState();
653
+ }
654
+
655
+ function languageFor(path) {
656
+ const ext = String(path ?? '').split('.').pop()?.toLowerCase() ?? '';
657
+ return LANG_BY_EXT[ext] ?? '';
658
+ }
659
+
660
+ /** 代码容器:左侧行号 + 右侧高亮代码,整体共用一个滚动区域。 */
661
+ function renderCode(container, code, path) {
662
+ const lines = String(code ?? '').split('\n');
663
+ const gutter = lines.map((_, index) => index + 1).join('\n');
664
+ const lang = languageFor(path);
665
+ container.innerHTML =
666
+ `<div class="code-scroll"><pre class="code-gutter">${gutter}</pre>` +
667
+ `<pre class="code-pre"><code${lang ? ` class="language-${escapeHtml(lang)}"` : ''}></code></pre></div>`;
668
+ const node = container.querySelector('code');
669
+ node.textContent = String(code ?? '');
670
+ if (window.hljs && lang && String(code ?? '').length <= 300_000) {
671
+ try {
672
+ window.hljs.highlightElement(node);
673
+ } catch {
674
+ /* 单个文件失败保持纯文本 */
675
+ }
676
+ }
677
+ }
678
+
679
+
513
680
  // ---------------- 聊天流 ----------------
514
681
  let controller = null;
515
682
 
@@ -579,18 +746,57 @@ async function send() {
579
746
  const botMsg = document.createElement('article');
580
747
  botMsg.className = 'msg assistant enter';
581
748
  botMsg.innerHTML = '<div class="msg-role">Banana</div>';
582
- const toolWrap = document.createElement('div');
583
- toolWrap.className = 'tool-group';
584
- const reasoning = document.createElement('div');
585
- reasoning.className = 'reasoning';
749
+
750
+ // 工具调用:默认折叠成一行工作摘要,失败时自动展开
751
+ const work = document.createElement('details');
752
+ work.className = 'work-group';
753
+ work.hidden = true;
754
+ const workSummary = document.createElement('summary');
755
+ workSummary.innerHTML =
756
+ '<span class="wg-dot"></span><span class="wg-title">正在运行</span><span class="wg-state"></span>';
757
+ const workBody = document.createElement('div');
758
+ workBody.className = 'tool-group-body';
759
+ work.append(workSummary, workBody);
760
+
761
+ // 思考过程:流式展开,回答开始后自动折叠
762
+ const reasoning = document.createElement('details');
763
+ reasoning.className = 'think';
586
764
  reasoning.hidden = true;
765
+ reasoning.open = true;
766
+ const reasonSummary = document.createElement('summary');
767
+ reasonSummary.innerHTML = '<span class="think-title">思考中…</span>';
768
+ const reasonBody = document.createElement('div');
769
+ reasonBody.className = 'think-body';
770
+ reasoning.append(reasonSummary, reasonBody);
771
+
587
772
  const body = document.createElement('div');
588
773
  body.className = 'msg-body caret';
589
774
  const meta = document.createElement('div');
590
775
  meta.className = 'turn-meta';
591
- botMsg.append(toolWrap, reasoning, body, meta);
776
+ botMsg.append(work, reasoning, body, meta);
592
777
  THREAD.appendChild(botMsg);
593
778
 
779
+ let reasoningStarted = 0;
780
+ let toolStarted = 0;
781
+ let toolCount = 0;
782
+ let toolErrors = false;
783
+ const finishReasoning = () => {
784
+ if (reasoning.hidden || reasoning.dataset.done === '1') return;
785
+ reasoning.dataset.done = '1';
786
+ reasoning.open = false;
787
+ const seconds = reasoningStarted ? ((Date.now() - reasoningStarted) / 1000).toFixed(1) : '0';
788
+ reasonSummary.querySelector('.think-title').textContent = `思考 · ${seconds}s`;
789
+ };
790
+ const finishWork = () => {
791
+ if (work.hidden || work.dataset.done === '1') return;
792
+ work.dataset.done = '1';
793
+ const seconds = toolStarted ? ((Date.now() - toolStarted) / 1000).toFixed(1) : '0';
794
+ workSummary.querySelector('.wg-title').textContent = `运行了 ${toolCount} 个工具`;
795
+ workSummary.querySelector('.wg-state').textContent = `${seconds}s${toolErrors ? ' · 有失败' : ''}`;
796
+ work.classList.toggle('has-error', toolErrors);
797
+ if (!toolErrors) work.open = false;
798
+ };
799
+
594
800
  const images = state.attachments.map((item) => item.path);
595
801
  state.attachments = [];
596
802
  renderAttachments();
@@ -639,9 +845,25 @@ async function send() {
639
845
  for (const line of chunk.split('\n')) {
640
846
  if (!line.startsWith('data: ')) continue;
641
847
  const event = JSON.parse(line.slice(6));
642
- if (event.type === 'text') { buffer += event.chunk; schedule(); }
643
- else if (event.type === 'reasoning') { reasoning.hidden = false; reasoning.textContent += event.chunk; }
644
- else if (event.type === 'tool_start') {
848
+ if (event.type === 'text') {
849
+ finishReasoning();
850
+ buffer += event.chunk;
851
+ schedule();
852
+ } else if (event.type === 'reasoning') {
853
+ if (!reasoningStarted) {
854
+ reasoningStarted = Date.now();
855
+ reasoning.hidden = false;
856
+ reasoning.open = true;
857
+ }
858
+ reasoning.hidden = false;
859
+ reasonBody.appendChild(document.createTextNode(event.chunk));
860
+ } else if (event.type === 'tool_start') {
861
+ if (!toolStarted) toolStarted = Date.now();
862
+ toolCount += 1;
863
+ work.hidden = false;
864
+ work.open = true;
865
+ workSummary.querySelector('.wg-title').textContent = `正在运行 ${toolCount} 个工具`;
866
+ workSummary.querySelector('.wg-state').textContent = '';
645
867
  const row = document.createElement('div');
646
868
  row.className = 'tool-row';
647
869
  row.innerHTML =
@@ -649,14 +871,15 @@ async function send() {
649
871
  `<span class="t-name">${escapeHtml(event.name)}</span>` +
650
872
  `<span class="t-detail">${escapeHtml(event.detail)}</span>` +
651
873
  '<span class="t-state"><span class="spin"></span></span>';
652
- toolWrap.appendChild(row);
874
+ workBody.appendChild(row);
653
875
  scrollToEnd(false);
654
876
  } else if (event.type === 'tool_end') {
655
- const rows = toolWrap.querySelectorAll('.tool-row');
877
+ const rows = workBody.querySelectorAll('.tool-row');
656
878
  const row = rows[rows.length - 1];
657
879
  if (row) {
658
880
  row.querySelector('.t-state').innerHTML = event.ok ? svg('check') : svg('x');
659
881
  row.classList.toggle('is-error', !event.ok);
882
+ if (!event.ok) toolErrors = true;
660
883
  if (event.detail) {
661
884
  row.classList.add('is-clickable');
662
885
  row.title = '点击展开输出';
@@ -668,12 +891,16 @@ async function send() {
668
891
  await post('approve', { id: event.id, allowed });
669
892
  } else if (event.type === 'error') {
670
893
  // 服务端提前收尾(没配 key、请求出错等):给出能照做的下一步
894
+ finishReasoning();
895
+ finishWork();
671
896
  body.classList.remove('caret');
672
897
  body.innerHTML = markdown(`**${escapeHtml(event.message ?? '出错了')}**`);
673
898
  if (event.hint) metaLine('提示', event.hint);
674
899
  if (event.code === 'no_api_key') openSettings();
675
900
  streamEnded = true;
676
901
  } else if (event.type === 'done') {
902
+ finishReasoning();
903
+ finishWork();
677
904
  body.classList.remove('caret');
678
905
  streamEnded = true;
679
906
  if (event.error) body.innerHTML = markdown(`**请求失败** ${escapeHtml(event.error)}`);
@@ -692,14 +919,17 @@ async function send() {
692
919
  state.sessions = sessions;
693
920
  renderSidebar();
694
921
  renderHeader();
922
+ if (state.workbench.open && state.workbench.tab === 'changes') void loadChanges(true);
695
923
  }
696
924
  }
697
925
  }
698
926
  }
699
927
  // 流结束了却没收到 done/error:多半是被中断,别让界面一直转圈
700
928
  if (!streamEnded) {
929
+ finishReasoning();
930
+ finishWork();
701
931
  body.classList.remove('caret');
702
- if (body.textContent === '' && toolWrap.childElementCount === 0) {
932
+ if (body.textContent === '' && workBody.childElementCount === 0) {
703
933
  body.innerHTML = markdown('这一轮没有返回内容。可以重试,或点「停止」后换个说法。');
704
934
  }
705
935
  await refresh();
@@ -709,8 +939,11 @@ async function send() {
709
939
  body.innerHTML = markdown(`**中断** ${escapeHtml(error.message)}`);
710
940
  await refresh();
711
941
  } finally {
942
+ finishReasoning();
943
+ finishWork();
712
944
  setBusy(false);
713
945
  scrollToEnd();
946
+ if (state.workbench.open && state.workbench.tab === 'changes') void loadChanges(true);
714
947
  }
715
948
  }
716
949
 
@@ -721,6 +954,11 @@ const THEME_LABEL = { auto: '跟随系统', light: '浅色', dark: '深色' };
721
954
  const THEME_ICON = { auto: 'contrast', light: 'sun', dark: 'moon' };
722
955
 
723
956
  function applyTheme(theme) {
957
+ // 主题切换时短暂开启颜色过渡,避免整页硬切
958
+ const root = document.documentElement;
959
+ root.classList.add('theme-anim');
960
+ clearTimeout(applyTheme.timer);
961
+ applyTheme.timer = setTimeout(() => root.classList.remove('theme-anim'), 300);
724
962
  if (theme === 'auto') delete document.documentElement.dataset.theme;
725
963
  else document.documentElement.dataset.theme = theme;
726
964
  try {
@@ -941,231 +1179,814 @@ async function attach(file) {
941
1179
  toast('已附加 ' + file.name);
942
1180
  }
943
1181
 
944
- // ---------------- 设置面板 ----------------
1182
+ // ---------------- 控制中心 ----------------
1183
+ const SETTINGS_NAV = [
1184
+ { id: 'model', label: '模型', icon: 'chip' },
1185
+ { id: 'appearance', label: '外观', icon: 'sun' },
1186
+ { id: 'terminal', label: '终端', icon: 'terminal' },
1187
+ { id: 'workspace', label: '工作区', icon: 'folder' },
1188
+ { id: 'plugins', label: '插件', icon: 'plug' },
1189
+ { id: 'about', label: '关于', icon: 'info' },
1190
+ ];
1191
+
1192
+ function openSettings(category) {
1193
+ if (category) state.settingsCategory = category;
1194
+ state.settingsScroll = 0;
1195
+ renderSettings();
1196
+ const sheet = $('settingsSheet');
1197
+ sheet.classList.remove('is-closing');
1198
+ sheet.hidden = false;
1199
+ document.body.classList.add('has-overlay');
1200
+ requestAnimationFrame(() => {
1201
+ $('settingsBody').scrollTop = 0;
1202
+ $('settingsSheet').querySelector('.settings-panel')?.focus?.();
1203
+ });
1204
+ }
1205
+
1206
+ function closeSettings() {
1207
+ const sheet = $('settingsSheet');
1208
+ if (sheet.hidden) return;
1209
+ state.settingsScroll = $('settingsBody').scrollTop;
1210
+ void hideAnimated(sheet, 'is-closing', 170).then(syncOverlayState);
1211
+ $('input')?.focus();
1212
+ }
1213
+
1214
+ function settingsCard() {
1215
+ const card = document.createElement('div');
1216
+ card.className = 'set-card';
1217
+ return card;
1218
+ }
1219
+
1220
+ function settingsRow(title, desc, control) {
1221
+ const row = document.createElement('div');
1222
+ row.className = 'set-row';
1223
+ const copy = document.createElement('div');
1224
+ copy.className = 'set-copy';
1225
+ copy.innerHTML = `<strong>${escapeHtml(title)}</strong>${desc ? `<span>${escapeHtml(desc)}</span>` : ''}`;
1226
+ row.appendChild(copy);
1227
+ if (control) {
1228
+ const holder = document.createElement('div');
1229
+ holder.className = 'set-control';
1230
+ holder.appendChild(control);
1231
+ row.appendChild(holder);
1232
+ }
1233
+ return row;
1234
+ }
1235
+
1236
+ function settingsButton(label, onClick, primary = false) {
1237
+ const button = document.createElement('button');
1238
+ button.className = `btn tiny${primary ? ' primary' : ''}`;
1239
+ button.textContent = label;
1240
+ button.addEventListener('click', onClick);
1241
+ return button;
1242
+ }
1243
+
1244
+ function settingsInput(value, placeholder, type = 'text') {
1245
+ const input = document.createElement('input');
1246
+ input.type = type;
1247
+ input.value = value ?? '';
1248
+ input.placeholder = placeholder ?? '';
1249
+ input.spellcheck = false;
1250
+ return input;
1251
+ }
1252
+
1253
+ function settingsSwitch(on, onChange) {
1254
+ const button = document.createElement('button');
1255
+ button.className = `switch${on ? ' is-on' : ''}`;
1256
+ button.type = 'button';
1257
+ button.setAttribute('role', 'switch');
1258
+ button.setAttribute('aria-checked', String(Boolean(on)));
1259
+ button.addEventListener('click', () => {
1260
+ const next = !button.classList.contains('is-on');
1261
+ button.classList.toggle('is-on', next);
1262
+ button.setAttribute('aria-checked', String(next));
1263
+ onChange(next);
1264
+ });
1265
+ return button;
1266
+ }
1267
+
1268
+ function settingsSeg(options, current, onChange) {
1269
+ const seg = document.createElement('div');
1270
+ seg.className = 'seg';
1271
+ for (const option of options) {
1272
+ const button = document.createElement('button');
1273
+ button.type = 'button';
1274
+ button.dataset.value = option.value;
1275
+ button.textContent = option.label;
1276
+ button.classList.toggle('is-on', option.value === current);
1277
+ button.addEventListener('click', () => {
1278
+ if (button.classList.contains('is-on')) return;
1279
+ seg.querySelectorAll('button').forEach((item) => item.classList.toggle('is-on', item === button));
1280
+ onChange(option.value);
1281
+ });
1282
+ seg.appendChild(button);
1283
+ }
1284
+ return seg;
1285
+ }
1286
+
1287
+ function settingsSection(title, sub) {
1288
+ const section = document.createElement('section');
1289
+ section.className = 'settings-section';
1290
+ section.innerHTML = `<h3 class="settings-title">${escapeHtml(title)}</h3>${sub ? `<p class="settings-sub">${escapeHtml(sub)}</p>` : ''}`;
1291
+ return section;
1292
+ }
1293
+
1294
+ async function saveSetting(action, payload) {
1295
+ try {
1296
+ const result = await post('action', { action, ...payload });
1297
+ if (result?.info) state.info = result.info;
1298
+ return result;
1299
+ } catch (error) {
1300
+ toast('保存失败:' + (error?.message ?? error));
1301
+ throw error;
1302
+ }
1303
+ }
1304
+
945
1305
  function renderSettings() {
946
1306
  const info = state.info;
1307
+ if (!info) return;
947
1308
  const body = $('settingsBody');
1309
+ const nav = $('settingsNav');
1310
+ const scroll = body.scrollTop || state.settingsScroll || 0;
1311
+ nav.innerHTML = '';
1312
+ for (const item of SETTINGS_NAV) {
1313
+ const button = document.createElement('button');
1314
+ button.innerHTML = `${svg(item.icon)}<span>${item.label}</span>`;
1315
+ button.classList.toggle('is-on', item.id === state.settingsCategory);
1316
+ button.addEventListener('click', () => {
1317
+ if (state.settingsCategory === item.id) return;
1318
+ state.settingsCategory = item.id;
1319
+ state.settingsScroll = 0;
1320
+ renderSettings();
1321
+ body.scrollTop = 0;
1322
+ });
1323
+ nav.appendChild(button);
1324
+ }
1325
+
948
1326
  body.innerHTML = '';
1327
+ const category = state.settingsCategory;
1328
+ if (category === 'model') renderModelSettings(body);
1329
+ else if (category === 'appearance') renderAppearanceSettings(body);
1330
+ else if (category === 'terminal') renderTerminalSettings(body);
1331
+ else if (category === 'workspace') renderWorkspaceSettings(body);
1332
+ else if (category === 'plugins') renderPluginSettings(body);
1333
+ else renderAboutSettings(body);
1334
+ requestAnimationFrame(() => { body.scrollTop = scroll; });
1335
+ }
949
1336
 
950
- const providerField = document.createElement('div');
951
- providerField.className = 'field';
952
- providerField.innerHTML =
953
- '<label>Provider</label><select>' +
954
- info.providers.map((item) => `<option value="${item.name}" ${item.current ? 'selected' : ''}>${item.name} — ${item.model}</option>`).join('') +
955
- '</select>';
956
- providerField.querySelector('select').addEventListener('change', async (event) => {
957
- await post('action', { action: 'provider', name: event.target.value });
958
- await refreshSettings();
1337
+ function renderModelSettings(body) {
1338
+ const info = state.info;
1339
+ const active = info.providers.find((item) => item.current);
1340
+ const section = settingsSection('模型', '选择 provider、模型和密钥。CLI 与 GUI 共用同一份配置。');
1341
+
1342
+ const card = settingsCard();
1343
+ const providerSelect = document.createElement('select');
1344
+ providerSelect.innerHTML = info.providers
1345
+ .map((item) => `<option value="${escapeHtml(item.name)}" ${item.current ? 'selected' : ''}>${escapeHtml(item.name)} · ${escapeHtml(item.model)}</option>`)
1346
+ .join('');
1347
+ providerSelect.addEventListener('change', async () => {
1348
+ await saveSetting('provider', { name: providerSelect.value });
1349
+ await refresh(false);
1350
+ renderSettings();
1351
+ toast('已切换到 ' + providerSelect.value);
959
1352
  });
960
- body.appendChild(providerField);
961
-
962
- const modelField = document.createElement('div');
963
- modelField.className = 'field';
964
- modelField.innerHTML = `<label>模型</label><div class="row"><input value="${escapeHtml(info.provider.model)}" /><button class="btn">保存</button></div>`;
965
- modelField.querySelector('button').addEventListener('click', async () => {
966
- const value = modelField.querySelector('input').value.trim();
967
- if (!value) return;
968
- await post('action', { action: 'model', value });
969
- await refreshSettings();
1353
+ card.appendChild(settingsRow('Provider', '切换后新消息使用这个 provider。', providerSelect));
1354
+
1355
+ const modelInput = settingsInput(info.provider.model, '模型名,例如 deepseek-chat');
1356
+ const saveModel = settingsButton('保存', async () => {
1357
+ const value = modelInput.value.trim();
1358
+ if (!value) return toast('请填写模型名');
1359
+ await saveSetting('model', { value });
1360
+ await refresh(false);
1361
+ renderSettings();
970
1362
  toast('模型已更新');
971
- });
972
- modelField.querySelector('input').addEventListener('keydown', (event) => {
973
- if (event.key === 'Enter') modelField.querySelector('button').click();
974
- });
975
- body.appendChild(modelField);
976
-
977
- // API key:留空表示不修改;提示可以用环境变量代替
978
- const active = info.providers.find((item) => item.current);
979
- const keyField = document.createElement('div');
980
- keyField.className = 'field';
981
- const keyPlaceholder = active?.keySaved
982
- ? '已保存(留空表示不修改)'
983
- : active?.keyEnv
984
- ? `默认读取环境变量 ${active.keyEnv}(当前${active.keyReady ? '已设置' : '未设置'})`
985
- : '粘贴 API key';
986
- keyField.innerHTML =
987
- '<label>API Key</label>' +
988
- `<div class="row"><input type="password" placeholder="${keyPlaceholder}" /><button class="btn">保存</button></div>` +
989
- `<div class="hint">${active?.keyEnv ? `默认读取环境变量 ${active.keyEnv};` : ''}更安全的做法是只设环境变量,配置文件里只留变量名。</div>`;
990
- keyField.querySelector('button').addEventListener('click', async () => {
991
- const input = keyField.querySelector('input');
992
- const value = input.value.trim();
993
- if (!value) {
994
- toast('留空表示不修改');
995
- return;
996
- }
997
- await post('action', { action: 'apiKey', value });
998
- input.value = '';
999
- await refreshSettings();
1363
+ }, true);
1364
+ modelInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') saveModel.click(); });
1365
+ const modelBox = document.createElement('div');
1366
+ modelBox.style.display = 'flex';
1367
+ modelBox.style.gap = '6px';
1368
+ modelBox.append(modelInput, saveModel);
1369
+ card.appendChild(settingsRow('模型', '保存后立即生效。', modelBox));
1370
+
1371
+ const keyInput = settingsInput('', active?.keySaved ? '已保存,留空表示不修改' : '粘贴 API Key', 'password');
1372
+ const saveKey = settingsButton('保存', async () => {
1373
+ const value = keyInput.value.trim();
1374
+ if (!value) return toast('留空表示不修改');
1375
+ await saveSetting('apiKey', { value });
1376
+ keyInput.value = '';
1377
+ await refresh(false);
1378
+ renderSettings();
1000
1379
  toast('API Key 已保存');
1380
+ }, true);
1381
+ keyInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') saveKey.click(); });
1382
+ const keyBox = document.createElement('div');
1383
+ keyBox.style.display = 'flex';
1384
+ keyBox.style.gap = '6px';
1385
+ keyBox.append(keyInput, saveKey);
1386
+ const keyHint = active?.keyEnv
1387
+ ? `也可以只设置环境变量 ${active.keyEnv},当前${active.keyReady ? '已就绪' : '未设置'}。`
1388
+ : '更安全的做法是使用环境变量,不要把 key 写进仓库。';
1389
+ card.appendChild(settingsRow('API Key', keyHint, keyBox));
1390
+ card.appendChild(
1391
+ settingsRow(
1392
+ '显示思考过程',
1393
+ '推理模型会展示思考内容;关闭后只保留最终回答。',
1394
+ settingsSwitch(info.showReasoning !== false, async (on) => {
1395
+ await saveSetting('showReasoning', { value: String(on) });
1396
+ await refresh(false);
1397
+ toast(on ? '已显示思考过程' : '已隐藏思考过程');
1398
+ }),
1399
+ ),
1400
+ );
1401
+ section.appendChild(card);
1402
+
1403
+ const promptCard = settingsCard();
1404
+ const stack = document.createElement('div');
1405
+ stack.className = 'set-stack';
1406
+ stack.innerHTML = '<div class="set-copy"><strong>系统提示词</strong><span>给模型的长期指令,会影响所有对话。</span></div>';
1407
+ const area = document.createElement('textarea');
1408
+ area.value = info.systemPrompt ?? '';
1409
+ area.placeholder = '例如:回答尽量简洁,优先给可执行命令。';
1410
+ stack.appendChild(area);
1411
+ const actions = document.createElement('div');
1412
+ actions.className = 'settings-actions';
1413
+ actions.append(
1414
+ settingsButton('恢复默认', async () => {
1415
+ area.value = '';
1416
+ await saveSetting('system', { value: '' });
1417
+ await refresh(false);
1418
+ renderSettings();
1419
+ toast('已清空,使用内置系统提示词');
1420
+ }),
1421
+ settingsButton('保存提示词', async () => {
1422
+ await saveSetting('system', { value: area.value });
1423
+ await refresh(false);
1424
+ toast('系统提示词已保存');
1425
+ }, true),
1426
+ );
1427
+ stack.appendChild(actions);
1428
+ promptCard.appendChild(stack);
1429
+ section.appendChild(promptCard);
1430
+ body.appendChild(section);
1431
+ }
1432
+
1433
+ function renderAppearanceSettings(body) {
1434
+ const saved = (() => {
1435
+ try {
1436
+ return localStorage.getItem('banana-theme') ?? 'auto';
1437
+ } catch {
1438
+ return 'auto';
1439
+ }
1440
+ })();
1441
+ const section = settingsSection('外观', '黑白主题,柔和对比。切换会同步终端和代码高亮。');
1442
+ const card = settingsCard();
1443
+ card.appendChild(
1444
+ settingsRow(
1445
+ '主题',
1446
+ '跟随系统最省心;也可以固定浅色或深色。',
1447
+ settingsSeg(
1448
+ [
1449
+ { value: 'auto', label: '跟随系统' },
1450
+ { value: 'light', label: '浅色' },
1451
+ { value: 'dark', label: '深色' },
1452
+ ],
1453
+ saved,
1454
+ (value) => {
1455
+ applyTheme(value);
1456
+ toast('主题:' + (value === 'auto' ? '跟随系统' : value === 'dark' ? '深色' : '浅色'));
1457
+ },
1458
+ ),
1459
+ ),
1460
+ );
1461
+ section.appendChild(card);
1462
+
1463
+ const motion = settingsCard();
1464
+ motion.appendChild(
1465
+ settingsRow('减少动效', '关闭大部分弹簧和入场动画,适合晕动或低性能设备。', settingsSwitch(
1466
+ document.documentElement.dataset.reduceMotion === '1',
1467
+ (on) => {
1468
+ if (on) document.documentElement.dataset.reduceMotion = '1';
1469
+ else delete document.documentElement.dataset.reduceMotion;
1470
+ localStorage.setItem('banana.reduceMotion', on ? '1' : '0');
1471
+ toast(on ? '已减少动效' : '已恢复弹力动画');
1472
+ },
1473
+ )),
1474
+ );
1475
+ section.appendChild(motion);
1476
+ body.appendChild(section);
1477
+ }
1478
+
1479
+ function renderTerminalSettings(body) {
1480
+ const section = settingsSection('终端', '真实 PTY,支持 PowerShell、cmd、Git Bash 和 WSL。关面板不会杀进程。');
1481
+ const card = settingsCard();
1482
+
1483
+ card.appendChild(
1484
+ settingsRow(
1485
+ '字号',
1486
+ '只影响终端显示,不改变 shell 行为。',
1487
+ settingsSeg(
1488
+ [12, 13, 14, 15, 16].map((size) => ({ value: String(size), label: `${size}px` })),
1489
+ String(term.fontSize),
1490
+ (value) => {
1491
+ term.fontSize = Number(value) || 13;
1492
+ localStorage.setItem(TERM_STORAGE.fontSize, String(term.fontSize));
1493
+ termRestyle();
1494
+ },
1495
+ ),
1496
+ ),
1497
+ );
1498
+
1499
+ const shellSelect = document.createElement('select');
1500
+ const preferred = localStorage.getItem(TERM_STORAGE.shell) || term.defaultShell || 'powershell';
1501
+ shellSelect.innerHTML = (term.shells.length ? term.shells : [{ id: 'powershell', name: 'PowerShell' }])
1502
+ .map((shell) => `<option value="${escapeHtml(shell.id)}" ${shell.id === preferred ? 'selected' : ''}>${escapeHtml(shell.name)}</option>`)
1503
+ .join('');
1504
+ shellSelect.addEventListener('change', () => {
1505
+ localStorage.setItem(TERM_STORAGE.shell, shellSelect.value);
1506
+ const picker = $('termShell');
1507
+ if (picker) picker.value = shellSelect.value;
1508
+ toast('新标签将使用 ' + (term.shells.find((item) => item.id === shellSelect.value)?.name ?? shellSelect.value));
1001
1509
  });
1002
- keyField.querySelector('input').addEventListener('keydown', (event) => {
1003
- if (event.key === 'Enter') keyField.querySelector('button').click();
1004
- });
1005
- body.appendChild(keyField);
1006
-
1007
- // 工作区:换目录后所有文件工具和命令都跟着换,所以放显眼位置
1008
- const workspaceField = document.createElement('div');
1009
- workspaceField.className = 'field';
1010
- workspaceField.innerHTML =
1011
- '<label>工作区</label>' +
1012
- `<div class="row"><input value="${escapeHtml(info.workspace ?? '')}" spellcheck="false" /><button class="btn">切换</button></div>` +
1013
- '<div class="hint">Banana 只能读写这个目录下的文件,命令也在这里执行。绝对路径,例如 D:\\project。</div>';
1014
- workspaceField.querySelector('button').addEventListener('click', async () => {
1015
- const input = workspaceField.querySelector('input');
1510
+ card.appendChild(settingsRow('默认 Shell', '新建终端标签时使用。', shellSelect));
1511
+
1512
+ const isTermOpen = state.workbench.open && state.workbench.tab === 'terminal';
1513
+ const openBtn = settingsButton(isTermOpen ? '收起终端' : '打开终端', () => {
1514
+ closeSettings();
1515
+ if (isTermOpen) closeWorkbench();
1516
+ else termOpen();
1517
+ }, true);
1518
+ card.appendChild(settingsRow('终端面板', '在右侧工作台打开,不会挡住输入框。快捷键 Ctrl+`。', openBtn));
1519
+ section.appendChild(card);
1520
+
1521
+ const help = settingsSection('常用快捷键', '');
1522
+ const helpCard = settingsCard();
1523
+ for (const [keys, text] of [
1524
+ ['Ctrl+`', '打开 / 收起终端工作台'],
1525
+ ['Ctrl+K', '全局命令中心'],
1526
+ ['Ctrl+Shift+F', '打开文件工作台'],
1527
+ ['Ctrl+Shift+G', '查看本会话改动'],
1528
+ ['Esc', '关闭最上层;在终端里留给 shell'],
1529
+ ['Enter / Shift+Enter', '发送 / 换行'],
1530
+ ['@', '引用项目文件'],
1531
+ ['/', '打开命令面板'],
1532
+ ]) {
1533
+ const row = settingsRow(keys, text);
1534
+ row.querySelector('.set-copy strong').style.fontFamily = 'var(--mono)';
1535
+ helpCard.appendChild(row);
1536
+ }
1537
+ help.appendChild(helpCard);
1538
+ body.append(section, help);
1539
+ }
1540
+
1541
+ function renderWorkspaceSettings(body) {
1542
+ const info = state.info;
1543
+ const section = settingsSection('工作区', '文件工具和命令都只能在这个目录下执行。');
1544
+ const card = settingsCard();
1545
+ const input = settingsInput(info.workspace ?? '', '绝对路径,例如 D:\\project');
1546
+ const switchBtn = settingsButton('切换', async () => {
1016
1547
  const value = input.value.trim();
1017
- if (!value) {
1018
- toast('请填写目录路径');
1019
- return;
1020
- }
1548
+ if (!value) return toast('请填写目录路径');
1021
1549
  try {
1022
- await post('action', { action: 'workspace', value });
1023
- await refreshSettings();
1550
+ await saveSetting('workspace', { value });
1551
+ await refresh(false);
1024
1552
  renderHeader();
1553
+ renderSettings();
1554
+ $('filesTree').innerHTML = '';
1025
1555
  toast('工作区已切换到 ' + value);
1026
1556
  } catch (error) {
1027
1557
  toast('切换失败:' + (error?.message ?? error));
1028
1558
  }
1029
- });
1030
- workspaceField.querySelector('input').addEventListener('keydown', (event) => {
1031
- if (event.key === 'Enter') workspaceField.querySelector('button').click();
1032
- });
1033
- body.appendChild(workspaceField);
1034
-
1035
- const terminalField = document.createElement('div');
1036
- terminalField.className = 'field';
1037
- terminalField.innerHTML =
1038
- '<label>终端</label><div class="row"><button class="btn">在界面里打开终端</button>' +
1039
- '<select class="tiny-select" aria-label="终端字号">' +
1040
- [12, 13, 14, 15, 16].map((size) => `<option value="${size}" ${size === term.fontSize ? 'selected' : ''}>${size}px</option>`).join('') +
1041
- '</select></div>' +
1042
- '<div class="hint">真实 shell(cmd / PowerShell / Git Bash / WSL),支持颜色和交互;停靠位置可在终端右上角切换,Ctrl+` 开关。</div>';
1043
- terminalField.querySelector('button').addEventListener('click', () => {
1044
- closeSettings();
1045
- termOpen();
1046
- });
1047
- terminalField.querySelector('select').addEventListener('change', (event) => {
1048
- term.fontSize = Number(event.target.value) || 13;
1049
- localStorage.setItem(TERM_STORAGE.fontSize, String(term.fontSize));
1050
- termRestyle();
1051
- });
1052
- body.appendChild(terminalField);
1053
-
1054
- const permField = document.createElement('div');
1055
- permField.className = 'field';
1056
- permField.innerHTML = '<label>权限</label>';
1057
- // 权限是小白最容易懵的地方,所以每种模式都写清楚"改了会发生什么"
1559
+ }, true);
1560
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter') switchBtn.click(); });
1561
+ const box = document.createElement('div');
1562
+ box.style.display = 'flex';
1563
+ box.style.gap = '6px';
1564
+ box.append(input, switchBtn);
1565
+ card.appendChild(settingsRow('当前工作区', '切换后插件也会重新加载项目目录。', box));
1566
+ section.appendChild(card);
1567
+
1568
+ const permSection = settingsSection('权限', '不确定就保持「每次问」。改动会立刻保存,CLI 和 GUI 共用。');
1569
+ const permCard = settingsCard();
1058
1570
  const PERM_INFO = {
1059
- shell: {
1060
- name: '执行命令',
1061
- hint: 'Banana 可以在你的电脑上运行命令(如 npm test、git status)。',
1062
- modes: {
1063
- ask: '每次执行前弹窗问你 —— 最安全,推荐新手用这个',
1064
- allow: '直接执行,不打扰你 —— 方便但风险自负',
1065
- deny: '完全禁止 —— Banana 只能读文件,不能动你的系统',
1066
- },
1067
- },
1068
- write: {
1069
- name: '写入文件',
1070
- hint: '修改或新建文件的能力。每次改动都可以用左下角「撤销」回滚。',
1071
- modes: {
1072
- ask: '每次改文件前给你看改动内容,你确认才写',
1073
- allow: '直接改,不再逐个确认',
1074
- deny: '禁止任何写入 —— 只读模式',
1075
- },
1076
- },
1077
- network: {
1078
- name: '联网',
1079
- hint: '允许 Banana 访问外部网络(搜索、抓网页)。',
1080
- modes: {
1081
- ask: '每次联网都问你',
1082
- allow: '允许联网(默认)',
1083
- deny: '完全断网,只能用本地信息',
1084
- },
1085
- },
1571
+ shell: { name: '执行命令', hint: '运行 npm test、git status 等命令。' },
1572
+ write: { name: '写入文件', hint: '新建或修改文件,可用左下角撤销回滚。' },
1573
+ network: { name: '联网', hint: '搜索和抓取网页。' },
1086
1574
  };
1087
1575
  for (const key of ['shell', 'write', 'network']) {
1088
1576
  const spec = PERM_INFO[key];
1089
- const row = document.createElement('div');
1090
- row.className = 'perm-row';
1091
- row.dataset.key = key;
1092
- const seg = document.createElement('div');
1093
- seg.className = 'seg';
1094
- seg.innerHTML = ['ask', 'allow', 'deny']
1095
- .map((mode) => {
1096
- const label = mode === 'ask' ? '每次问' : mode === 'allow' ? '直接执行' : '禁止';
1097
- return `<button data-mode="${mode}" class="${info.permissions[key] === mode ? 'is-on' : ''}">${label}</button>`;
1098
- })
1099
- .join('');
1100
- seg.addEventListener('click', async (event) => {
1101
- const button = event.target.closest('[data-mode]');
1102
- if (!button) return;
1103
- const mode = button.dataset.mode;
1104
- // 立即反馈,失败再回滚并提示,避免看起来"点不动"
1105
- seg.querySelectorAll('[data-mode]').forEach((item) => item.classList.toggle('is-on', item === button));
1106
- const detail = row.querySelector('.perm-detail');
1107
- if (detail) detail.textContent = spec.modes[mode];
1577
+ permCard.appendChild(
1578
+ settingsRow(
1579
+ spec.name,
1580
+ spec.hint,
1581
+ settingsSeg(
1582
+ [
1583
+ { value: 'ask', label: '每次问' },
1584
+ { value: 'allow', label: '允许' },
1585
+ { value: 'deny', label: '禁止' },
1586
+ ],
1587
+ info.permissions[key],
1588
+ async (mode) => {
1589
+ await saveSetting('permission', { name: key, value: mode });
1590
+ await refresh(false);
1591
+ toast(`「${spec.name}」已设为:${mode === 'ask' ? '每次问' : mode === 'allow' ? '允许' : '禁止'}`);
1592
+ },
1593
+ ),
1594
+ ),
1595
+ );
1596
+ }
1597
+ permSection.appendChild(permCard);
1598
+ body.append(section, permSection);
1599
+ }
1600
+
1601
+ function pluginBadge(text) {
1602
+ const badge = document.createElement('span');
1603
+ badge.className = 'plugin-badge';
1604
+ badge.textContent = text;
1605
+ return badge;
1606
+ }
1607
+
1608
+ function renderPluginSettings(body) {
1609
+ const section = settingsSection('插件工坊', '插件就是 .mjs 文件。可以生成模板、查看错误、试运行和启用停用。');
1610
+
1611
+ const actions = document.createElement('div');
1612
+ actions.className = 'settings-actions';
1613
+ actions.style.justifyContent = 'flex-start';
1614
+ actions.style.marginBottom = '12px';
1615
+ actions.append(
1616
+ settingsButton('重新加载', async () => {
1617
+ try {
1618
+ state.plugins = await post('plugins', { action: 'reload' });
1619
+ await refresh(false);
1620
+ renderSettings();
1621
+ toast('插件已重新加载');
1622
+ } catch (error) {
1623
+ toast('重载失败:' + (error?.message ?? error));
1624
+ }
1625
+ }, true),
1626
+ settingsButton('新建模板', async () => {
1108
1627
  try {
1109
- await post('action', { action: 'permission', name: key, value: mode });
1628
+ const result = await post('plugins', { action: 'create' });
1629
+ state.plugins = result;
1110
1630
  await refresh(false);
1111
- toast(`「${spec.name}」已设为:${mode === 'ask' ? '每次问' : mode === 'allow' ? '直接执行' : '禁止'}`);
1631
+ renderSettings();
1632
+ toast('已创建 ' + result.file);
1112
1633
  } catch (error) {
1113
- seg.querySelectorAll('[data-mode]').forEach((item) => item.classList.toggle('is-on', item.dataset.mode !== mode));
1114
- if (detail) detail.textContent = spec.modes[info.permissions[key]];
1115
- toast('保存失败:' + error.message);
1634
+ toast('创建失败:' + (error?.message ?? error));
1635
+ }
1636
+ }),
1637
+ settingsButton('打开全局目录', () => {
1638
+ post('plugins', { action: 'open', scope: 'global' }).catch((error) => toast('打开失败:' + error.message));
1639
+ }),
1640
+ settingsButton('打开项目目录', () => {
1641
+ post('plugins', { action: 'open', scope: 'project' }).catch((error) => toast('打开失败:' + error.message));
1642
+ }),
1643
+ );
1644
+ section.appendChild(actions);
1645
+
1646
+ const list = document.createElement('div');
1647
+ list.innerHTML = '<div class="plugin-empty">读取插件中…</div>';
1648
+ section.appendChild(list);
1649
+ body.appendChild(section);
1650
+
1651
+ void (async () => {
1652
+ let data;
1653
+ try {
1654
+ data = await get('plugins');
1655
+ state.plugins = data;
1656
+ } catch (error) {
1657
+ list.innerHTML = `<div class="plugin-empty">${escapeHtml(error.message)}</div>`;
1658
+ return;
1659
+ }
1660
+ if (state.settingsCategory !== 'plugins') return;
1661
+ list.innerHTML = '';
1662
+ if (!data.plugins?.length) {
1663
+ const empty = document.createElement('div');
1664
+ empty.className = 'plugin-empty';
1665
+ empty.textContent = '还没有插件。点「新建模板」生成第一个,或把 .mjs 放进插件目录。';
1666
+ list.appendChild(empty);
1667
+ }
1668
+ for (const plugin of data.plugins ?? []) {
1669
+ list.appendChild(renderPluginCard(plugin));
1670
+ }
1671
+ const dirs = document.createElement('div');
1672
+ dirs.className = 'hint';
1673
+ dirs.style.marginTop = '12px';
1674
+ dirs.textContent = '全局:' + (data.dirs?.find((dir) => dir.id === 'global')?.path ?? '') + ' 项目:' + (data.dirs?.find((dir) => dir.id === 'project')?.path ?? '');
1675
+ list.appendChild(dirs);
1676
+ })();
1677
+ }
1678
+
1679
+ function renderPluginCard(plugin) {
1680
+ const card = document.createElement('div');
1681
+ card.className = `plugin-card${plugin.enabled ? '' : ' is-off'}`;
1682
+ const main = document.createElement('div');
1683
+ main.className = 'plugin-main';
1684
+ const name = document.createElement('div');
1685
+ name.className = 'plugin-name';
1686
+ name.textContent = plugin.name || plugin.file.split(/[\\/]/).pop();
1687
+ name.appendChild(pluginBadge(plugin.ok ? (plugin.disabled ? '已停用' : '已加载') : '加载失败'));
1688
+ if (plugin.approval && plugin.approval !== 'never') name.appendChild(pluginBadge(plugin.approval));
1689
+ main.appendChild(name);
1690
+ const desc = document.createElement('div');
1691
+ desc.className = 'plugin-desc';
1692
+ desc.textContent = plugin.description || (plugin.ok ? '没有填写说明。' : '插件文件存在错误,模型暂时无法调用。');
1693
+ main.appendChild(desc);
1694
+ const file = document.createElement('div');
1695
+ file.className = 'plugin-file';
1696
+ file.textContent = plugin.file;
1697
+ main.appendChild(file);
1698
+ if (plugin.error) {
1699
+ const error = document.createElement('div');
1700
+ error.className = 'plugin-error';
1701
+ error.textContent = plugin.error;
1702
+ main.appendChild(error);
1703
+ }
1704
+
1705
+ const acts = document.createElement('div');
1706
+ acts.className = 'plugin-actions';
1707
+ if (plugin.ok) {
1708
+ acts.appendChild(
1709
+ settingsSwitch(plugin.enabled, async (on) => {
1710
+ try {
1711
+ const result = await post('plugins', { action: 'toggle', name: plugin.name, disabled: !on });
1712
+ state.plugins = result;
1713
+ await refresh(false);
1714
+ renderSettings();
1715
+ toast(on ? `已启用 ${plugin.name}` : `已停用 ${plugin.name}`);
1716
+ } catch (error) {
1717
+ toast('操作失败:' + (error?.message ?? error));
1718
+ renderSettings();
1719
+ }
1720
+ }),
1721
+ );
1722
+ const test = settingsButton('试运行', () => {
1723
+ const existing = card.querySelector('.plugin-test');
1724
+ if (existing) {
1725
+ existing.remove();
1726
+ return;
1116
1727
  }
1728
+ const box = document.createElement('div');
1729
+ box.className = 'plugin-test';
1730
+ box.style.cssText = 'margin-top:10px;display:flex;flex-direction:column;gap:6px';
1731
+ const area = document.createElement('textarea');
1732
+ area.className = 'plugin-json';
1733
+ area.value = '{\n "text": "hello"\n}';
1734
+ const run = settingsButton('运行', async () => {
1735
+ output.textContent = '运行中…';
1736
+ try {
1737
+ const result = await post('plugins', { action: 'test', file: plugin.file, input: area.value });
1738
+ output.textContent = result.result ?? '(无输出)';
1739
+ } catch (error) {
1740
+ output.textContent = '失败:' + (error?.message ?? error);
1741
+ }
1742
+ }, true);
1743
+ const output = document.createElement('pre');
1744
+ output.className = 'plugin-error';
1745
+ output.textContent = '输入 JSON,然后点运行。';
1746
+ box.append(area, run, output);
1747
+ main.appendChild(box);
1117
1748
  });
1749
+ acts.appendChild(test);
1750
+ }
1751
+ card.append(main, acts);
1752
+ return card;
1753
+ }
1118
1754
 
1119
- const block = document.createElement('div');
1120
- block.className = 'perm-block';
1121
- const head = document.createElement('div');
1122
- head.className = 'perm-head';
1123
- head.innerHTML = `<span class="perm-name">${escapeHtml(spec.name)}</span>`;
1124
- head.appendChild(seg);
1125
- const desc = document.createElement('div');
1126
- desc.className = 'hint';
1127
- desc.textContent = spec.hint;
1128
- const detail = document.createElement('div');
1129
- detail.className = 'perm-detail';
1130
- detail.textContent = spec.modes[info.permissions[key]];
1131
- block.append(head, desc, detail);
1132
- row.appendChild(block);
1133
- permField.appendChild(row);
1755
+ function renderAboutSettings(body) {
1756
+ const info = state.info;
1757
+ const section = settingsSection('关于 Banana', '一个把 CLI 内核完整搬进图形界面的本地 agent。');
1758
+ const card = settingsCard();
1759
+ card.appendChild(settingsRow('版本', 'CLI 与 GUI 使用同一套 agent 循环和工具。', pluginBadge('v' + (info.version ?? '0.6.0'))));
1760
+ card.appendChild(settingsRow('工作区', info.workspace ?? '', null));
1761
+ card.appendChild(settingsRow('工具数量', `${info.tools?.length ?? 0} 个`, null));
1762
+ card.appendChild(settingsRow('平台', info.platform === 'win32' ? 'Windows' : info.platform === 'darwin' ? 'macOS' : 'Linux', null));
1763
+ section.appendChild(card);
1764
+
1765
+ const tip = settingsCard();
1766
+ tip.appendChild(settingsRow('命令中心', '按 Ctrl+K 搜索会话、文件、动作和设置。', settingsButton('打开', () => { closeSettings(); openCommandCenter(); })));
1767
+ tip.appendChild(settingsRow('项目文件', '代码支持行号、全屏查看和选中后问 AI。', settingsButton('打开', () => { closeSettings(); openFiles(); })));
1768
+ section.appendChild(tip);
1769
+ body.appendChild(section);
1770
+ }
1771
+
1772
+ // ---------------- 右侧工作台 ----------------
1773
+ const WB_STORAGE = { width: 'banana.wb.width', tab: 'banana.wb.tab' };
1774
+ const WB_MIN = 340;
1775
+ const WB_DEFAULT = 420;
1776
+
1777
+ function wbApplyWidth(width) {
1778
+ const max = Math.max(WB_MIN, Math.min(820, window.innerWidth * 0.72));
1779
+ state.workbench.width = Math.max(WB_MIN, Math.min(Number(width) || WB_DEFAULT, max));
1780
+ $('workbench').style.setProperty('--wb-width', `${Math.round(state.workbench.width)}px`);
1781
+ }
1782
+
1783
+ function wbIsNarrow() {
1784
+ return window.matchMedia('(max-width: 980px)').matches;
1785
+ }
1786
+
1787
+ function openWorkbench(tab) {
1788
+ const wb = $('workbench');
1789
+ if (tab) state.workbench.tab = tab;
1790
+ wb.classList.remove('is-closing');
1791
+ wb.hidden = false;
1792
+ state.workbench.open = true;
1793
+ wbApplyWidth(state.workbench.width);
1794
+ // 强制读一次布局,保证从 0 宽开始过渡(不依赖可能被后台节流的 rAF)
1795
+ void wb.offsetWidth;
1796
+ wb.classList.add('open');
1797
+ setWorkbenchTab(state.workbench.tab);
1798
+ $('wbScrim').hidden = !wbIsNarrow();
1799
+ syncOverlayState();
1800
+ }
1801
+
1802
+ function closeWorkbench() {
1803
+ const wb = $('workbench');
1804
+ if (!state.workbench.open) return;
1805
+ state.workbench.open = false;
1806
+ wb.classList.remove('open');
1807
+ wb.classList.add('is-closing');
1808
+ $('wbScrim').hidden = true;
1809
+ setTimeout(() => {
1810
+ if (state.workbench.open) return;
1811
+ wb.hidden = true;
1812
+ wb.classList.remove('is-closing');
1813
+ syncOverlayState();
1814
+ $('input')?.focus();
1815
+ }, 280);
1816
+ }
1817
+
1818
+ function setWorkbenchTab(tab) {
1819
+ if (!['terminal', 'files', 'changes'].includes(tab)) tab = 'terminal';
1820
+ state.workbench.tab = tab;
1821
+ try {
1822
+ localStorage.setItem(WB_STORAGE.tab, tab);
1823
+ } catch {}
1824
+ $('wbTabs').querySelectorAll('.wb-tab').forEach((node) => {
1825
+ const on = node.dataset.tab === tab;
1826
+ node.classList.toggle('is-on', on);
1827
+ node.setAttribute('aria-selected', String(on));
1828
+ });
1829
+ $('workbench').querySelectorAll('.wb-pane').forEach((node) => {
1830
+ node.classList.toggle('active', node.dataset.pane === tab);
1831
+ });
1832
+ if (tab === 'terminal') {
1833
+ termEnsure();
1834
+ requestAnimationFrame(() => termFitActive());
1835
+ } else if (tab === 'files') {
1836
+ if (!$('filesTree').childElementCount) void loadTree('.');
1837
+ } else if (tab === 'changes') {
1838
+ void loadChanges(true);
1134
1839
  }
1135
- const note = document.createElement('div');
1136
- note.className = 'hint perm-note';
1137
- note.textContent = '改动立刻生效,并保存在配置里(CLI 和 GUI 共用同一份设置)。不确定就保持「每次问」。';
1138
- permField.appendChild(note);
1139
- body.appendChild(permField);
1140
-
1141
- const toolsField = document.createElement('div');
1142
- toolsField.className = 'field';
1143
- toolsField.innerHTML =
1144
- '<label>工具</label><div class="hint">' +
1145
- info.tools.map((tool) => `${escapeHtml(tool.name)} <span style="opacity:.6">${tool.permission}</span>`).join('、') +
1146
- '</div>';
1147
- body.appendChild(toolsField);
1148
-
1149
- const sysField = document.createElement('div');
1150
- sysField.className = 'field';
1151
- sysField.innerHTML = '<label>系统提示词</label>';
1152
- const textarea = document.createElement('textarea');
1153
- textarea.rows = 6;
1154
- textarea.style.cssText = 'border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-size:13px;resize:vertical';
1155
- textarea.value = state.systemPrompt ?? '';
1156
- sysField.append(textarea);
1157
- const saveRow = document.createElement('div');
1158
- saveRow.innerHTML = '<button class="btn">保存提示词</button>';
1159
- saveRow.querySelector('button').addEventListener('click', async () => {
1160
- await post('action', { action: 'system', value: textarea.value });
1161
- toast('已保存');
1840
+ }
1841
+
1842
+ function initWorkbench() {
1843
+ try {
1844
+ const savedWidth = Number(localStorage.getItem(WB_STORAGE.width));
1845
+ if (savedWidth) state.workbench.width = savedWidth;
1846
+ const savedTab = localStorage.getItem(WB_STORAGE.tab);
1847
+ if (savedTab) state.workbench.tab = savedTab;
1848
+ } catch {}
1849
+ wbApplyWidth(state.workbench.width);
1850
+ $('wbTabs').querySelectorAll('.wb-tab').forEach((node) => {
1851
+ node.addEventListener('click', () => setWorkbenchTab(node.dataset.tab));
1852
+ });
1853
+ $('wbClose').addEventListener('click', closeWorkbench);
1854
+ $('wbScrim').addEventListener('click', closeWorkbench);
1855
+ $('changesRefresh').addEventListener('click', () => loadChanges(true));
1856
+ $('wbResizer').addEventListener('pointerdown', (event) => {
1857
+ event.preventDefault();
1858
+ $('workbench').classList.add('is-resizing');
1859
+ const move = (moveEvent) => {
1860
+ wbApplyWidth(window.innerWidth - moveEvent.clientX);
1861
+ if (state.workbench.tab === 'terminal') termFitActive();
1862
+ };
1863
+ const up = () => {
1864
+ window.removeEventListener('pointermove', move);
1865
+ window.removeEventListener('pointerup', up);
1866
+ $('workbench').classList.remove('is-resizing');
1867
+ try {
1868
+ localStorage.setItem(WB_STORAGE.width, String(Math.round(state.workbench.width)));
1869
+ } catch {}
1870
+ if (state.workbench.tab === 'terminal') termFitActive();
1871
+ };
1872
+ window.addEventListener('pointermove', move);
1873
+ window.addEventListener('pointerup', up);
1874
+ });
1875
+ window.addEventListener('resize', () => {
1876
+ wbApplyWidth(state.workbench.width);
1877
+ $('wbScrim').hidden = !state.workbench.open || !wbIsNarrow();
1878
+ if (state.workbench.tab === 'terminal') termFitActive();
1162
1879
  });
1163
- sysField.append(saveRow);
1164
- body.appendChild(sysField);
1880
+ }
1881
+
1882
+ // ---------------- 变更(Diff) ----------------
1883
+ async function loadChanges(force = false) {
1884
+ if (!force && state.changes) {
1885
+ renderChanges();
1886
+ return;
1887
+ }
1888
+ const list = $('changesList');
1889
+ list.innerHTML = '<div class="hint" style="padding:12px">读取改动…</div>';
1890
+ try {
1891
+ const data = await get('changes');
1892
+ state.changes = data;
1893
+ renderChanges();
1894
+ } catch (error) {
1895
+ list.innerHTML = `<div class="hint" style="padding:12px">${escapeHtml(error.message)}</div>`;
1896
+ }
1897
+ }
1898
+
1899
+ function renderChanges() {
1900
+ const list = $('changesList');
1901
+ const detail = $('changesDetail');
1902
+ list.innerHTML = '';
1903
+ const turns = state.changes?.turns ?? [];
1904
+ if (!turns.length) {
1905
+ list.innerHTML = '<div class="hint" style="padding:12px">还没有文件改动。让 Banana 改一次文件后,这里会出现增删行。</div>';
1906
+ detail.innerHTML = '<div class="hint">没有可显示的改动。</div>';
1907
+ return;
1908
+ }
1909
+ let total = 0;
1910
+ for (const turn of turns) {
1911
+ const group = document.createElement('div');
1912
+ group.className = 'changes-group';
1913
+ const head = document.createElement('div');
1914
+ head.className = 'changes-turn';
1915
+ head.textContent = new Date(turn.at).toLocaleString();
1916
+ group.appendChild(head);
1917
+ for (const file of turn.files) {
1918
+ total += 1;
1919
+ const button = document.createElement('button');
1920
+ button.className = 'change-file';
1921
+ button.innerHTML =
1922
+ `<span class="cf-name">${escapeHtml(file.path)}</span>` +
1923
+ `<span class="cf-count"><i class="plus">+${file.additions}</i><i class="minus">-${file.deletions}</i></span>`;
1924
+ button.addEventListener('click', () => {
1925
+ list.querySelectorAll('.change-file.is-on').forEach((node) => node.classList.remove('is-on'));
1926
+ button.classList.add('is-on');
1927
+ renderDiff(file);
1928
+ });
1929
+ group.appendChild(button);
1930
+ }
1931
+ list.appendChild(group);
1932
+ }
1933
+ $('changesTitle').textContent = `本会话改动 · ${total} 个文件`;
1934
+ // 默认打开第一个有内容的文件
1935
+ const firstFile = turns.find((turn) => turn.files.length)?.files[0];
1936
+ if (firstFile) {
1937
+ const firstButton = list.querySelector('.change-file');
1938
+ firstButton?.classList.add('is-on');
1939
+ renderDiff(firstFile);
1940
+ } else {
1941
+ detail.innerHTML = '<div class="hint">没有可显示的改动。</div>';
1942
+ }
1943
+ }
1944
+
1945
+ function renderDiff(file) {
1946
+ const detail = $('changesDetail');
1947
+ detail.innerHTML = '';
1948
+ const head = document.createElement('div');
1949
+ head.className = 'diff-head';
1950
+ head.innerHTML =
1951
+ `<span class="diff-path">${escapeHtml(file.path)}</span>` +
1952
+ `<span class="diff-stat"><i class="plus">+${file.additions}</i><i class="minus">-${file.deletions}</i></span>` +
1953
+ (file.missing ? '<span class="plugin-badge">文件已不存在</span>' : '');
1954
+ detail.appendChild(head);
1955
+ const body = document.createElement('div');
1956
+ body.className = 'diff-body';
1957
+ const lines = file.lines ?? [];
1958
+ if (!lines.length) {
1959
+ body.innerHTML = '<div class="hint" style="padding:10px">没有行级差异(可能只是换行符变化)。</div>';
1960
+ } else {
1961
+ for (const line of lines) {
1962
+ const row = document.createElement('div');
1963
+ row.className = `diff-line ${line.type}`;
1964
+ const oldNo = line.oldLine ?? '';
1965
+ const newNo = line.newLine ?? '';
1966
+ row.innerHTML =
1967
+ `<span class="diff-no">${oldNo}</span><span class="diff-no">${newNo}</span>` +
1968
+ `<span class="diff-sign">${line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' '}</span>` +
1969
+ `<span class="diff-text"></span>`;
1970
+ row.querySelector('.diff-text').textContent = line.text;
1971
+ body.appendChild(row);
1972
+ }
1973
+ }
1974
+ if (file.truncated) {
1975
+ const note = document.createElement('div');
1976
+ note.className = 'hint';
1977
+ note.style.padding = '8px 10px';
1978
+ note.textContent = '改动较大,只显示前面一部分。';
1979
+ body.appendChild(note);
1980
+ }
1981
+ detail.appendChild(body);
1982
+ detail.scrollTop = 0;
1165
1983
  }
1166
1984
 
1167
1985
  // ---------------- 文件面板 ----------------
1986
+
1987
+
1168
1988
  const FILE_ICON = { dir: 'folder', file: 'file' };
1989
+ const FILE_STORAGE = { tree: 'banana.files.tree', wrap: 'banana.files.wrap' };
1169
1990
 
1170
1991
  async function loadTree(path = '.', container = $('filesTree')) {
1171
1992
  container.innerHTML = '<div class="hint" style="padding:8px 10px">读取中…</div>';
@@ -1179,6 +2000,7 @@ async function loadTree(path = '.', container = $('filesTree')) {
1179
2000
  entries.forEach((entry, index) => {
1180
2001
  const row = document.createElement('button');
1181
2002
  row.className = 'file-row';
2003
+ row.dataset.path = entry.path;
1182
2004
  row.style.setProperty('--i', String(Math.min(index, 14)));
1183
2005
  row.innerHTML =
1184
2006
  `<span class="tool-caret">${entry.type === 'dir' ? svg('chevron') : ''}</span>` +
@@ -1208,33 +2030,120 @@ async function loadTree(path = '.', container = $('filesTree')) {
1208
2030
  }
1209
2031
  }
1210
2032
 
2033
+ function applyFilesLayout() {
2034
+ const panel = $('filesPanel');
2035
+ const tree = Number(localStorage.getItem(FILE_STORAGE.tree));
2036
+ if (tree) panel.style.setProperty('--tree-height', `${tree}px`);
2037
+ const wrap = localStorage.getItem(FILE_STORAGE.wrap) === '1';
2038
+ $('previewBody').classList.toggle('is-wrap', wrap);
2039
+ $('viewerBody').classList.toggle('is-wrap', wrap);
2040
+ $('previewWrap').classList.toggle('is-on', wrap);
2041
+ $('viewerWrap').classList.toggle('is-on', wrap);
2042
+ }
2043
+
2044
+ function openFiles() {
2045
+ applyFilesLayout();
2046
+ $('filesTitle').textContent = `项目文件 · ${state.info?.workspace ?? ''}`;
2047
+ openWorkbench('files');
2048
+ }
2049
+
2050
+ function openChanges() {
2051
+ openWorkbench('changes');
2052
+ void loadChanges(true);
2053
+ }
2054
+
2055
+ function closeFiles() {
2056
+ closeWorkbench();
2057
+ }
2058
+
2059
+ function toggleFiles() {
2060
+ if (!$('workbench').hidden && state.workbench.tab === 'files') closeWorkbench();
2061
+ else openFiles();
2062
+ }
2063
+
2064
+ function closePreview() {
2065
+ const panel = $('filesPanel');
2066
+ const box = $('filesPreview');
2067
+ if (box.hidden) return;
2068
+ panel.classList.remove('previewing');
2069
+ box.hidden = true;
2070
+ state.preview = null;
2071
+ }
2072
+
1211
2073
  async function openFile(path) {
1212
2074
  const box = $('filesPreview');
1213
2075
  const body = $('previewBody');
2076
+ $('filesPanel').classList.add('previewing');
1214
2077
  box.hidden = false;
1215
2078
  $('previewName').textContent = path;
1216
- body.textContent = '读取中…';
2079
+ $('insertPath').dataset.path = path;
2080
+ body.innerHTML = '<div class="hint" style="padding:14px">读取中…</div>';
2081
+ document.querySelectorAll('.file-row.is-active').forEach((node) => node.classList.remove('is-active'));
2082
+ document.querySelectorAll('.file-row').forEach((node) => {
2083
+ if (node.dataset.path === path) node.classList.add('is-active');
2084
+ });
1217
2085
  try {
1218
2086
  const data = await get(`file?path=${encodeURIComponent(path)}`);
1219
- $('insertPath').dataset.path = path;
1220
- if (data.binary) body.textContent = `二进制文件(${data.bytes} 字节),无法预览。`;
1221
- else if (data.tooLarge) body.textContent = `文件较大(${data.bytes} 字节),未加载。`;
1222
- else highlightPreview(body, path, data.content ?? '');
1223
- document.querySelectorAll('.file-row.is-active').forEach((node) => node.classList.remove('is-active'));
2087
+ state.preview = { path, code: data.content ?? '', binary: Boolean(data.binary), tooLarge: Boolean(data.tooLarge) };
2088
+ if (data.binary) {
2089
+ body.innerHTML = `<div class="hint" style="padding:14px">二进制文件(${data.bytes} 字节),无法预览。</div>`;
2090
+ } else if (data.tooLarge) {
2091
+ body.innerHTML = `<div class="hint" style="padding:14px">文件较大(${data.bytes} 字节),未加载。</div>`;
2092
+ } else {
2093
+ renderCode(body, data.content ?? '', path);
2094
+ }
1224
2095
  } catch (error) {
1225
- body.textContent = error.message;
2096
+ body.innerHTML = `<div class="hint" style="padding:14px">${escapeHtml(error.message)}</div>`;
1226
2097
  }
1227
2098
  }
1228
2099
 
1229
- async function toggleFiles() {
2100
+ function openViewer() {
2101
+ const preview = state.preview;
2102
+ if (!preview?.code) return toast('没有可查看的代码');
2103
+ $('viewerName').textContent = preview.path;
2104
+ renderCode($('viewerBody'), preview.code, preview.path);
2105
+ applyFilesLayout();
2106
+ $('codeViewer').classList.remove('is-closing');
2107
+ $('codeViewer').hidden = false;
2108
+ document.body.classList.add('has-overlay');
2109
+ }
2110
+
2111
+ function closeViewer() {
2112
+ const viewer = $('codeViewer');
2113
+ if (viewer.hidden) return;
2114
+ void hideAnimated(viewer, 'is-closing', 160).then(syncOverlayState);
2115
+ }
2116
+
2117
+ function toggleWrap() {
2118
+ const on = !$('previewBody').classList.contains('is-wrap');
2119
+ $('previewBody').classList.toggle('is-wrap', on);
2120
+ $('viewerBody').classList.toggle('is-wrap', on);
2121
+ $('previewWrap').classList.toggle('is-on', on);
2122
+ $('viewerWrap').classList.toggle('is-on', on);
2123
+ localStorage.setItem(FILE_STORAGE.wrap, on ? '1' : '0');
2124
+ }
2125
+
2126
+ function initFileResize() {
1230
2127
  const panel = $('filesPanel');
1231
- panel.hidden = !panel.hidden;
1232
- if (!panel.hidden && !$('filesTree').childElementCount) {
1233
- $('filesTitle').textContent = `项目文件 · ${state.info?.workspace ?? ''}`;
1234
- await loadTree('.');
1235
- }
2128
+ $('filesDivider').addEventListener('pointerdown', (event) => {
2129
+ event.preventDefault();
2130
+ const split = $('filesSplit');
2131
+ const move = (moveEvent) => {
2132
+ const rect = split.getBoundingClientRect();
2133
+ const height = Math.max(76, Math.min(rect.height - 140, moveEvent.clientY - rect.top));
2134
+ panel.style.setProperty('--tree-height', `${height}px`);
2135
+ };
2136
+ const up = () => {
2137
+ window.removeEventListener('pointermove', move);
2138
+ window.removeEventListener('pointerup', up);
2139
+ localStorage.setItem(FILE_STORAGE.tree, String(Math.round($('filesTree').getBoundingClientRect().height)));
2140
+ };
2141
+ window.addEventListener('pointermove', move);
2142
+ window.addEventListener('pointerup', up);
2143
+ });
1236
2144
  }
1237
2145
 
2146
+
1238
2147
  // ---------------- 工具输出详情 ----------------
1239
2148
  function toggleToolOutput(row, detail, isError) {
1240
2149
  const existing = row.nextElementSibling;
@@ -1251,31 +2160,15 @@ function toggleToolOutput(row, detail, isError) {
1251
2160
  }
1252
2161
 
1253
2162
  // ---------------- 启动 ----------------
1254
- function openSettings() {
1255
- renderSettings();
1256
- $('settingsSheet').hidden = false;
1257
- }
1258
-
1259
- function closeSettings() {
1260
- $('settingsSheet').hidden = true;
1261
- // 收掉动画后再清空内容,避免关闭瞬间出现内容跳动
1262
- setTimeout(() => { if ($('settingsSheet').hidden) $('settingsBody').innerHTML = ''; }, 240);
1263
- }
1264
-
1265
2163
  // ---------------- 内嵌终端(xterm + PTY) ----------------
1266
2164
  const TERM_FONT = '"Cascadia Mono", "JetBrains Mono", "SF Mono", Consolas, "Microsoft YaHei", monospace';
1267
2165
  const TERM_STORAGE = {
1268
- dock: 'banana.term.dock',
1269
- size: 'banana.term.size',
1270
- pos: 'banana.term.pos',
1271
2166
  fontSize: 'banana.term.fontSize',
1272
2167
  shell: 'banana.term.shell',
1273
2168
  };
1274
2169
 
1275
2170
  const term = {
1276
2171
  open: false,
1277
- dock: localStorage.getItem(TERM_STORAGE.dock) || 'bottom',
1278
- size: Number(localStorage.getItem(TERM_STORAGE.size)) || 280,
1279
2172
  fontSize: Number(localStorage.getItem(TERM_STORAGE.fontSize)) || 13,
1280
2173
  shells: [],
1281
2174
  defaultShell: '',
@@ -1324,77 +2217,49 @@ function termActiveTab() {
1324
2217
  return term.tabs.find((tab) => tab.id === term.activeId) ?? null;
1325
2218
  }
1326
2219
 
1327
- function termUpdateCwd(cwd) {
1328
- const label = $('termCwd');
1329
- if (label && cwd) label.textContent = cwd;
1330
- }
1331
-
1332
- function termPersistSize() {
1333
- localStorage.setItem(TERM_STORAGE.size, String(Math.round(term.size)));
1334
- localStorage.setItem(TERM_STORAGE.dock, term.dock);
1335
- }
1336
-
1337
- function termApplyDock(dock, persist = true) {
1338
- term.dock = dock;
1339
- const panel = $('terminalPanel');
1340
- const workspace = $('workspace');
1341
- panel.dataset.dock = dock;
1342
- workspace.dataset.dock = dock;
1343
- panel.style.removeProperty('left');
1344
- panel.style.removeProperty('top');
1345
- panel.style.removeProperty('right');
1346
- panel.style.removeProperty('bottom');
1347
- panel.style.width = '';
1348
- panel.style.height = '';
1349
- if (dock === 'bottom' || dock === 'top') {
1350
- panel.style.height = `${term.size}px`;
1351
- } else if (dock === 'left' || dock === 'right') {
1352
- panel.style.width = `${term.size}px`;
1353
- } else {
1354
- panel.style.width = `${Math.min(680, Math.max(360, Math.round(workspace.clientWidth * 0.62)))}px`;
1355
- panel.style.height = `${Math.min(420, Math.max(220, Math.round(workspace.clientHeight * 0.55)))}px`;
1356
- const saved = termReadPos();
1357
- if (saved) {
1358
- panel.style.left = `${saved.x}px`;
1359
- panel.style.top = `${saved.y}px`;
1360
- }
1361
- }
1362
- if (persist) termPersistSize();
1363
- requestAnimationFrame(() => {
1364
- termActiveTab()?.fit.fit();
1365
- });
1366
- }
1367
-
1368
- function termReadPos() {
2220
+ function termFitActive() {
2221
+ if ($('workbench').hidden || state.workbench.tab !== 'terminal') return;
2222
+ const tab = termActiveTab();
2223
+ if (!tab) return;
1369
2224
  try {
1370
- const raw = JSON.parse(localStorage.getItem(TERM_STORAGE.pos) || 'null');
1371
- return raw && Number.isFinite(raw.x) && Number.isFinite(raw.y) ? raw : null;
2225
+ tab.fit.fit();
2226
+ tab.sendResize();
1372
2227
  } catch {
1373
- return null;
2228
+ /* 面板还没布局完成 */
1374
2229
  }
1375
2230
  }
1376
2231
 
2232
+ function termUpdateCwd(cwd) {
2233
+ const label = $('termCwd');
2234
+ if (label && cwd) label.textContent = cwd;
2235
+ }
2236
+
2237
+ let termShellsPromise = null;
1377
2238
  async function termLoadShells() {
1378
- if (term.loadedShells) return;
2239
+ if (termShellsPromise) return termShellsPromise;
1379
2240
  term.loadedShells = true;
1380
- try {
1381
- const data = await get('shells');
1382
- term.shells = Array.isArray(data.shells) ? data.shells : [];
1383
- term.defaultShell = data.default || term.shells[0]?.id || 'cmd';
1384
- const select = $('termShell');
1385
- const preferred = localStorage.getItem(TERM_STORAGE.shell);
1386
- select.innerHTML = term.shells
1387
- .map((shell) => `<option value="${escapeHtml(shell.id)}">${escapeHtml(shell.name)}</option>`)
1388
- .join('');
1389
- select.value = term.shells.some((shell) => shell.id === preferred) ? preferred : term.defaultShell;
1390
- select.addEventListener('change', () => {
1391
- localStorage.setItem(TERM_STORAGE.shell, select.value);
1392
- termCreateTab(select.value);
1393
- });
1394
- } catch (error) {
1395
- term.shells = [{ id: 'cmd', name: '终端' }];
1396
- term.defaultShell = 'cmd';
1397
- }
2241
+ termShellsPromise = (async () => {
2242
+ try {
2243
+ const data = await get('shells');
2244
+ term.shells = Array.isArray(data.shells) ? data.shells : [];
2245
+ term.defaultShell = data.default || term.shells[0]?.id || 'cmd';
2246
+ const select = $('termShell');
2247
+ const preferred = localStorage.getItem(TERM_STORAGE.shell);
2248
+ select.innerHTML = term.shells
2249
+ .map((shell) => `<option value="${escapeHtml(shell.id)}">${escapeHtml(shell.name)}</option>`)
2250
+ .join('');
2251
+ select.value = term.shells.some((shell) => shell.id === preferred) ? preferred : term.defaultShell;
2252
+ select.addEventListener('change', () => {
2253
+ localStorage.setItem(TERM_STORAGE.shell, select.value);
2254
+ closeTermMenu();
2255
+ termCreateTab(select.value);
2256
+ });
2257
+ } catch {
2258
+ term.shells = [{ id: 'cmd', name: '终端' }];
2259
+ term.defaultShell = 'cmd';
2260
+ }
2261
+ })();
2262
+ return termShellsPromise;
1398
2263
  }
1399
2264
 
1400
2265
  function termRenderTabs() {
@@ -1482,10 +2347,10 @@ function termConnect(tab) {
1482
2347
  }
1483
2348
  });
1484
2349
  ws.addEventListener('close', () => {
1485
- if (!tab.alive || !term.open) return;
2350
+ if (!tab.alive) return;
1486
2351
  // 服务重启或网络抖动时自动重连;服务端会按 tab.termId 把会话接回来
1487
2352
  setTimeout(() => {
1488
- if (tab.alive && term.open && (!tab.ws || tab.ws.readyState > 1)) termConnect(tab);
2353
+ if (tab.alive && (!tab.ws || tab.ws.readyState > 1)) termConnect(tab);
1489
2354
  }, 900);
1490
2355
  });
1491
2356
 
@@ -1495,11 +2360,12 @@ function termConnect(tab) {
1495
2360
  }
1496
2361
 
1497
2362
  function termCreateTab(shellId) {
1498
- if (!term.open) {
1499
- termOpen();
1500
- return null;
2363
+ if (!term.shells.length) {
2364
+ void termLoadShells().then(() => {
2365
+ if (term.shells.length) termCreateTab(shellId);
2366
+ });
2367
+ return;
1501
2368
  }
1502
- termLoadShells();
1503
2369
  const shell = term.shells.find((item) => item.id === shellId) ?? term.shells[0];
1504
2370
  const name = shell?.name ?? '终端';
1505
2371
  const pane = document.createElement('div');
@@ -1511,7 +2377,7 @@ function termCreateTab(shellId) {
1511
2377
  cursorStyle: 'bar',
1512
2378
  fontFamily: TERM_FONT,
1513
2379
  fontSize: term.fontSize,
1514
- lineHeight: 1.25,
2380
+ lineHeight: 1.45,
1515
2381
  letterSpacing: 0,
1516
2382
  scrollback: 8000,
1517
2383
  allowTransparency: true,
@@ -1543,14 +2409,10 @@ function termCreateTab(shellId) {
1543
2409
  terminal.onResize(() => tab.sendResize());
1544
2410
  termRenderTabs();
1545
2411
  termActivate(tab.id);
1546
- requestAnimationFrame(() => {
1547
- try {
1548
- fit.fit();
1549
- } catch {
1550
- /* 忽略 */
1551
- }
1552
- termConnect(tab);
1553
- });
2412
+ // 先连 WebSocket(不依赖页面可见性),再等布局完成 fit
2413
+ termConnect(tab);
2414
+ requestAnimationFrame(() => termFitActive());
2415
+ setTimeout(() => termFitActive(), 320);
1554
2416
  return tab;
1555
2417
  }
1556
2418
 
@@ -1584,38 +2446,38 @@ function termCloseTab(id) {
1584
2446
  }
1585
2447
  }
1586
2448
 
1587
- function termOpen() {
1588
- const panel = $('terminalPanel');
1589
- termApplyDock(term.dock, false);
1590
- if (!term.open) {
1591
- term.open = true;
1592
- panel.hidden = false;
1593
- requestAnimationFrame(() => panel.classList.add('show'));
2449
+ function termEnsure() {
2450
+ if (term.tabs.length) {
2451
+ termActivate(term.activeId);
2452
+ return;
1594
2453
  }
1595
- const ensure = () => {
1596
- if (term.tabs.length === 0) termCreateTab($('termShell')?.value || term.defaultShell);
1597
- else termActivate(term.activeId);
2454
+ const create = () => {
2455
+ if (term.tabs.length) {
2456
+ termActivate(term.activeId);
2457
+ return;
2458
+ }
2459
+ termCreateTab($('termShell')?.value || term.defaultShell);
1598
2460
  };
1599
- if (term.loadedShells) ensure();
1600
- else termLoadShells().then(ensure);
2461
+ if (term.shells.length) create();
2462
+ else void termLoadShells().then(create);
2463
+ }
2464
+
2465
+ function termOpen() {
2466
+ openWorkbench('terminal');
1601
2467
  termUpdateCwd(state.info?.workspace ?? '');
2468
+ setTimeout(() => {
2469
+ termFitActive();
2470
+ termActiveTab()?.terminal.focus();
2471
+ }, 320);
1602
2472
  }
1603
2473
 
1604
2474
  function termClose() {
1605
- term.open = false;
1606
- const panel = $('terminalPanel');
1607
- panel.classList.remove('show');
1608
- panel.classList.add('closing');
1609
- setTimeout(() => {
1610
- if (term.open) return;
1611
- panel.hidden = true;
1612
- panel.classList.remove('closing');
1613
- }, 180);
2475
+ closeWorkbench();
1614
2476
  }
1615
2477
 
1616
2478
  function termToggle() {
1617
- if (term.open) termClose();
1618
- else termOpen();
2479
+ if (!state.workbench.open || state.workbench.tab !== 'terminal') termOpen();
2480
+ else closeWorkbench();
1619
2481
  }
1620
2482
 
1621
2483
  function termRestyle() {
@@ -1623,85 +2485,39 @@ function termRestyle() {
1623
2485
  for (const tab of term.tabs) {
1624
2486
  tab.terminal.options.theme = theme;
1625
2487
  tab.terminal.options.fontSize = term.fontSize;
1626
- requestAnimationFrame(() => {
1627
- try {
1628
- tab.fit.fit();
1629
- } catch {
1630
- /* 忽略 */
1631
- }
1632
- });
1633
2488
  }
2489
+ termFitActive();
1634
2490
  }
1635
2491
 
1636
2492
  function bindTerminal() {
1637
2493
  $('termBtn').innerHTML = svg('terminal');
1638
2494
  $('termAdd').innerHTML = svg('plus');
1639
- $('termClear').innerHTML = svg('trash');
1640
- $('termClose').innerHTML = svg('x');
1641
- $('termDock').innerHTML = svg('panel');
2495
+ $('termMore').innerHTML = svg('dots');
1642
2496
  $('termBtn').addEventListener('click', termToggle);
1643
- $('termClose').addEventListener('click', termClose);
1644
2497
  $('termAdd').addEventListener('click', () => {
2498
+ closeTermMenu();
1645
2499
  termCreateTab($('termShell')?.value || term.defaultShell);
1646
2500
  });
1647
- $('termClear').addEventListener('click', () => termActiveTab()?.terminal.clear());
1648
- $('termDock').addEventListener('click', () => {
1649
- const order = ['bottom', 'right', 'left', 'float'];
1650
- const next = order[(order.indexOf(term.dock) + 1) % order.length];
1651
- termApplyDock(next);
1652
- toast(`终端停靠在${next === 'bottom' ? '底部' : next === 'top' ? '顶部' : next === 'right' ? '右侧' : next === 'left' ? '左侧' : '浮动'}`);
2501
+ $('termMore').addEventListener('click', (event) => {
2502
+ event.stopPropagation();
2503
+ $('termMenu').hidden = !$('termMenu').hidden;
1653
2504
  });
1654
-
1655
- // 拖动边缘调整大小(浮动态拖标题栏移动位置)
1656
- const grip = $('termGrip');
1657
- grip.addEventListener('pointerdown', (event) => {
1658
- event.preventDefault();
1659
- const workspace = $('workspace');
1660
- const rect = workspace.getBoundingClientRect();
1661
- const move = (moveEvent) => {
1662
- let size;
1663
- if (term.dock === 'bottom') size = rect.bottom - moveEvent.clientY;
1664
- else if (term.dock === 'top') size = moveEvent.clientY - rect.top;
1665
- else if (term.dock === 'right') size = rect.right - moveEvent.clientX;
1666
- else size = moveEvent.clientX - rect.left;
1667
- term.size = Math.min(Math.max(160, size), (term.dock === 'left' || term.dock === 'right' ? rect.width : rect.height) - 160);
1668
- if (term.dock === 'bottom' || term.dock === 'top') $('terminalPanel').style.height = `${term.size}px`;
1669
- else $('terminalPanel').style.width = `${term.size}px`;
1670
- termActiveTab()?.fit.fit();
1671
- };
1672
- const up = () => {
1673
- window.removeEventListener('pointermove', move);
1674
- window.removeEventListener('pointerup', up);
1675
- termPersistSize();
1676
- };
1677
- window.addEventListener('pointermove', move);
1678
- window.addEventListener('pointerup', up);
2505
+ $('termAnalyze').addEventListener('click', () => {
2506
+ closeTermMenu();
2507
+ analyzeTerminal();
1679
2508
  });
1680
-
1681
- const panel = $('terminalPanel');
1682
- panel.addEventListener('pointerdown', (event) => {
1683
- if (term.dock !== 'float') return;
1684
- if (event.target.closest('button, select, .term-tab, .term-grip')) return;
1685
- const workspace = $('workspace');
1686
- const rect = workspace.getBoundingClientRect();
1687
- const panelRect = panel.getBoundingClientRect();
1688
- const offsetX = event.clientX - panelRect.left;
1689
- const offsetY = event.clientY - panelRect.top;
1690
- const move = (moveEvent) => {
1691
- const x = Math.min(Math.max(0, moveEvent.clientX - rect.left - offsetX), rect.width - 240);
1692
- const y = Math.min(Math.max(0, moveEvent.clientY - rect.top - offsetY), rect.height - 80);
1693
- panel.style.left = `${x}px`;
1694
- panel.style.top = `${y}px`;
1695
- };
1696
- const up = () => {
1697
- window.removeEventListener('pointermove', move);
1698
- window.removeEventListener('pointerup', up);
1699
- const x = parseFloat(panel.style.left) || 0;
1700
- const y = parseFloat(panel.style.top) || 0;
1701
- localStorage.setItem(TERM_STORAGE.pos, JSON.stringify({ x, y }));
1702
- };
1703
- window.addEventListener('pointermove', move);
1704
- window.addEventListener('pointerup', up);
2509
+ $('termClear').addEventListener('click', () => {
2510
+ closeTermMenu();
2511
+ termActiveTab()?.terminal.clear();
2512
+ });
2513
+ $('termCopy').addEventListener('click', () => {
2514
+ closeTermMenu();
2515
+ const text = termActiveTab()?.terminal.getSelection?.() ?? '';
2516
+ if (text) copyText(text);
2517
+ else toast('先在终端里选中文字');
2518
+ });
2519
+ document.addEventListener('click', (event) => {
2520
+ if (!$('termMenu').hidden && !event.target.closest('#termMenu, #termMore')) closeTermMenu();
1705
2521
  });
1706
2522
 
1707
2523
  window.addEventListener('keydown', (event) => {
@@ -1711,10 +2527,8 @@ function bindTerminal() {
1711
2527
  }
1712
2528
  });
1713
2529
 
1714
- const observer = new ResizeObserver(() => {
1715
- if (term.open) termActiveTab()?.fit.fit();
1716
- });
1717
- observer.observe($('workspace'));
2530
+ const observer = new ResizeObserver(() => termFitActive());
2531
+ observer.observe($('workbench'));
1718
2532
 
1719
2533
  document.addEventListener('banana:theme', () => {
1720
2534
  if (term.tabs.length) termRestyle();
@@ -1722,6 +2536,329 @@ function bindTerminal() {
1722
2536
  termUpdateCwd(state.info?.workspace ?? '');
1723
2537
  }
1724
2538
 
2539
+ function closeTermMenu() {
2540
+ const menu = $('termMenu');
2541
+ if (menu) menu.hidden = true;
2542
+ }
2543
+
2544
+ // ---------------- 命令中心(Ctrl+K) ----------------
2545
+ const CC_GROUPS = ['会话', '动作', '设置', '命令', '文件'];
2546
+
2547
+ function ccActions() {
2548
+ return [
2549
+ { title: '新建对话', sub: '开始一个干净的会话', icon: 'plus', run: () => $('newChat').click() },
2550
+ { title: '打开项目文件', sub: '浏览、全屏查看、引用文件', icon: 'panel', run: openFiles },
2551
+ { title: '查看本会话改动', sub: '按文件查看增删行,审阅 agent 的修改', icon: 'diff', run: openChanges },
2552
+ { title: '打开终端', sub: '右侧工作台,不遮挡输入框', icon: 'terminal', run: termOpen },
2553
+ { title: '打开控制中心', sub: '模型、外观、终端、工作区、插件', icon: 'sliders', run: () => openSettings() },
2554
+ { title: '插件工坊', sub: '启用、停用、生成模板、试运行插件', icon: 'plug', run: () => openSettings('plugins') },
2555
+ { title: '切换主题', sub: '浅色 / 深色 / 跟随系统', icon: 'sun', run: cycleTheme },
2556
+ { title: '撤销上一轮改动', sub: '把文件恢复到上一轮对话之前', icon: 'undo', run: () => $('undoBtn').click() },
2557
+ ];
2558
+ }
2559
+
2560
+ function openCommandCenter() {
2561
+ const cc = $('commandCenter');
2562
+ if (!cc.hidden && !cc.classList.contains('is-closing')) {
2563
+ $('ccInput').select();
2564
+ return;
2565
+ }
2566
+ if (!$('settingsSheet').hidden) closeSettings();
2567
+ state.ccIndex = 0;
2568
+ state.ccFiles = [];
2569
+ $('ccInput').value = '';
2570
+ cc.classList.remove('is-closing');
2571
+ cc.hidden = false;
2572
+ renderCommandCenter('');
2573
+ syncOverlayState();
2574
+ requestAnimationFrame(() => {
2575
+ $('ccInput').focus();
2576
+ $('ccInput').select();
2577
+ });
2578
+ }
2579
+
2580
+ function closeCommandCenter() {
2581
+ const cc = $('commandCenter');
2582
+ if (cc.hidden) return;
2583
+ void hideAnimated(cc, 'is-closing', 140).then(syncOverlayState);
2584
+ $('input')?.focus();
2585
+ }
2586
+
2587
+ let ccFileTimer = 0;
2588
+ let ccFileSeq = 0;
2589
+ function scheduleCommandFiles(query) {
2590
+ clearTimeout(ccFileTimer);
2591
+ if (!query.trim()) return;
2592
+ const seq = ++ccFileSeq;
2593
+ ccFileTimer = setTimeout(async () => {
2594
+ try {
2595
+ const data = await get(`find?q=${encodeURIComponent(query.trim())}&limit=24`);
2596
+ if (seq !== ccFileSeq || $('commandCenter').hidden) return;
2597
+ state.ccFiles = data.files ?? [];
2598
+ renderCommandCenter($('ccInput').value);
2599
+ } catch {
2600
+ /* 文件搜索失败不打扰主流程 */
2601
+ }
2602
+ }, 150);
2603
+ }
2604
+
2605
+ function renderCommandCenter(query) {
2606
+ const q = query.trim().toLowerCase();
2607
+ const hit = (text) => !q || String(text ?? '').toLowerCase().includes(q);
2608
+ const items = [];
2609
+
2610
+ const sessions = state.sessions
2611
+ .filter((item) => hit(item.title) || hit('会话'))
2612
+ .slice(0, q ? 5 : 4)
2613
+ .map((item) => ({
2614
+ group: '会话',
2615
+ title: item.title || '新对话',
2616
+ sub: `${item.turns} 轮 · ${relativeTime(item.updatedAt)}`,
2617
+ icon: 'message',
2618
+ run: () => switchSession(item.id),
2619
+ }));
2620
+ items.push(...sessions);
2621
+
2622
+ for (const action of ccActions()) {
2623
+ if (hit(action.title) || hit(action.sub)) items.push({ ...action, group: '动作' });
2624
+ }
2625
+
2626
+ for (const nav of SETTINGS_NAV) {
2627
+ const title = `设置 · ${nav.label}`;
2628
+ if (hit(title)) {
2629
+ items.push({ group: '设置', title, sub: '打开控制中心对应的分类', icon: nav.icon, run: () => openSettings(nav.id) });
2630
+ }
2631
+ }
2632
+
2633
+ for (const command of commandList) {
2634
+ const title = `/${command.name}`;
2635
+ if (hit(title) || hit(command.summary)) {
2636
+ items.push({
2637
+ group: '命令',
2638
+ title,
2639
+ sub: command.summary,
2640
+ icon: 'command',
2641
+ run: () => {
2642
+ insertComposer(`/${command.name} `);
2643
+ $('input').focus();
2644
+ },
2645
+ });
2646
+ }
2647
+ }
2648
+
2649
+ for (const path of state.ccFiles ?? []) {
2650
+ const name = path.split('/').pop();
2651
+ items.push({
2652
+ group: '文件',
2653
+ title: name,
2654
+ sub: path,
2655
+ icon: 'file',
2656
+ run: () => {
2657
+ openFiles();
2658
+ void openFile(path);
2659
+ },
2660
+ });
2661
+ }
2662
+
2663
+ state.ccItems = items;
2664
+ if (!items.length) {
2665
+ $('ccResults').innerHTML = '<div class="cc-empty">没有匹配结果,换个关键词试试。</div>';
2666
+ state.ccIndex = 0;
2667
+ return;
2668
+ }
2669
+ state.ccIndex = Math.max(0, Math.min(state.ccIndex, items.length - 1));
2670
+ paintCommandCenter(items);
2671
+ }
2672
+
2673
+ function paintCommandCenter(items) {
2674
+ const box = $('ccResults');
2675
+ box.innerHTML = '';
2676
+ let group = '';
2677
+ items.forEach((item, index) => {
2678
+ if (item.group !== group) {
2679
+ group = item.group;
2680
+ const head = document.createElement('div');
2681
+ head.className = 'cc-group';
2682
+ head.textContent = group;
2683
+ box.appendChild(head);
2684
+ }
2685
+ const button = document.createElement('button');
2686
+ button.type = 'button';
2687
+ button.className = `cc-item${index === state.ccIndex ? ' is-on' : ''}`;
2688
+ button.innerHTML =
2689
+ `<span class="cc-item-icon">${svg(item.icon)}</span>` +
2690
+ `<span class="cc-item-main"><span class="cc-item-title">${escapeHtml(item.title)}</span>` +
2691
+ `${item.sub ? `<span class="cc-item-sub">${escapeHtml(item.sub)}</span>` : ''}</span>`;
2692
+ button.addEventListener('pointerenter', () => {
2693
+ if (state.ccIndex === index) return;
2694
+ state.ccIndex = index;
2695
+ box.querySelectorAll('.cc-item').forEach((node, i) => node.classList.toggle('is-on', i === index));
2696
+ });
2697
+ button.addEventListener('click', () => runCommandCenterItem(item));
2698
+ box.appendChild(button);
2699
+ });
2700
+ scrollCommandCenterActive();
2701
+ }
2702
+
2703
+ function scrollCommandCenterActive() {
2704
+ const box = $('ccResults');
2705
+ const active = box.querySelectorAll('.cc-item')[state.ccIndex];
2706
+ active?.scrollIntoView({ block: 'nearest' });
2707
+ }
2708
+
2709
+ function moveCommandCenter(delta) {
2710
+ if (!state.ccItems?.length) return;
2711
+ state.ccIndex = (state.ccIndex + delta + state.ccItems.length) % state.ccItems.length;
2712
+ const buttons = $('ccResults').querySelectorAll('.cc-item');
2713
+ buttons.forEach((node, index) => node.classList.toggle('is-on', index === state.ccIndex));
2714
+ scrollCommandCenterActive();
2715
+ }
2716
+
2717
+ function runCommandCenterItem(item) {
2718
+ if (!item) return;
2719
+ closeCommandCenter();
2720
+ setTimeout(() => item.run(), 60);
2721
+ }
2722
+
2723
+ // ---------------- 悬停提示 ----------------
2724
+ function initTooltips() {
2725
+ const tip = document.createElement('div');
2726
+ tip.className = 'tooltip';
2727
+ tip.hidden = true;
2728
+ document.body.appendChild(tip);
2729
+ let timer = 0;
2730
+ let target = null;
2731
+
2732
+ const place = () => {
2733
+ if (!target) return;
2734
+ const rect = target.getBoundingClientRect();
2735
+ const box = tip.getBoundingClientRect();
2736
+ const x = Math.max(8, Math.min(rect.left + rect.width / 2 - box.width / 2, window.innerWidth - box.width - 8));
2737
+ const below = rect.bottom + 9;
2738
+ const y = below + box.height > window.innerHeight - 8 ? Math.max(8, rect.top - box.height - 9) : below;
2739
+ tip.style.left = `${x}px`;
2740
+ tip.style.top = `${y}px`;
2741
+ };
2742
+
2743
+ const hide = () => {
2744
+ clearTimeout(timer);
2745
+ target = null;
2746
+ tip.classList.remove('is-on');
2747
+ setTimeout(() => {
2748
+ if (!tip.classList.contains('is-on')) tip.hidden = true;
2749
+ }, 120);
2750
+ };
2751
+
2752
+ document.addEventListener('pointerover', (event) => {
2753
+ const node = event.target.closest?.('[title], [data-tip]');
2754
+ if (!node) return;
2755
+ const title = node.getAttribute('title');
2756
+ if (title) {
2757
+ node.dataset.tip = title;
2758
+ node.removeAttribute('title');
2759
+ }
2760
+ const text = node.dataset.tip;
2761
+ if (!text) return;
2762
+ clearTimeout(timer);
2763
+ target = node;
2764
+ timer = setTimeout(() => {
2765
+ if (target !== node) return;
2766
+ tip.textContent = text;
2767
+ tip.hidden = false;
2768
+ tip.classList.remove('is-on');
2769
+ requestAnimationFrame(() => {
2770
+ place();
2771
+ tip.classList.add('is-on');
2772
+ });
2773
+ }, 380);
2774
+ });
2775
+
2776
+ document.addEventListener('pointerout', (event) => {
2777
+ if (!target) return;
2778
+ const related = event.relatedTarget;
2779
+ if (related && target.contains(related)) return;
2780
+ hide();
2781
+ });
2782
+
2783
+ document.addEventListener('pointerdown', hide, true);
2784
+ window.addEventListener('scroll', hide, true);
2785
+ window.addEventListener('blur', hide);
2786
+ }
2787
+
2788
+ // ---------------- 选中文本工具条 ----------------
2789
+ function initSelectionTools() {
2790
+ document.addEventListener('mouseup', (event) => {
2791
+ setTimeout(() => {
2792
+ const node = event.target instanceof Element ? event.target : null;
2793
+ if (node?.closest('#terminalPanel')) {
2794
+ const tab = termActiveTab();
2795
+ const text = tab?.terminal.getSelection?.() ?? '';
2796
+ if (text.trim()) {
2797
+ showSelectionTools(event.clientX, event.clientY, [
2798
+ { label: '分析输出', run: () => { termClose(); askAboutText(text, '', 'terminal'); } },
2799
+ { label: '复制', run: () => copyText(text) },
2800
+ ]);
2801
+ } else hideSelectionTools();
2802
+ return;
2803
+ }
2804
+ const host = node?.closest('.thread, .files-code, .viewer-body');
2805
+ const text = window.getSelection()?.toString() ?? '';
2806
+ if (host && text.trim().length > 1) {
2807
+ const path = host.classList.contains('files-code') || host.classList.contains('viewer-body') ? state.preview?.path : '';
2808
+ showSelectionTools(event.clientX, event.clientY, [
2809
+ { label: '问 AI', run: () => askAboutText(text, path) },
2810
+ { label: '复制', run: () => copyText(text) },
2811
+ { label: '插入输入框', run: () => { insertComposer(text.trim()); hideSelectionTools(); } },
2812
+ ]);
2813
+ } else hideSelectionTools();
2814
+ }, 20);
2815
+ });
2816
+ document.addEventListener('selectionchange', () => {
2817
+ if (!window.getSelection()?.toString().trim() && !$('selectionTools').hidden) hideSelectionTools();
2818
+ });
2819
+ }
2820
+
2821
+ // ---------------- 终端输出分析 ----------------
2822
+ function analyzeTerminal() {
2823
+ const tab = termActiveTab();
2824
+ if (!tab) return toast('还没有打开终端');
2825
+ let text = tab.terminal.getSelection?.() ?? '';
2826
+ if (!text.trim()) {
2827
+ const buffer = tab.terminal.buffer.active;
2828
+ const lines = [];
2829
+ const start = Math.max(0, buffer.length - 180);
2830
+ for (let i = start; i < buffer.length; i += 1) lines.push(buffer.getLine(i)?.translateToString(true) ?? '');
2831
+ text = lines.join('\n').trim();
2832
+ }
2833
+ if (!text.trim()) return toast('终端还没有输出');
2834
+ termClose();
2835
+ askAboutText(text, '', 'terminal');
2836
+ }
2837
+
2838
+ // ---------------- 桌面窗口控制 ----------------
2839
+ function initDesktop() {
2840
+ const api = window.bananaDesktop;
2841
+ if (!api) return;
2842
+ document.body.classList.add('desktop');
2843
+ if (!api.frameless) {
2844
+ // macOS 保留原生红绿灯,只启用拖动区域
2845
+ document.body.classList.add('mac-titlebar');
2846
+ return;
2847
+ }
2848
+ const controls = $('winControls');
2849
+ controls.hidden = false;
2850
+ $('winMin').innerHTML = svg('minimize');
2851
+ $('winMax').innerHTML = svg('maximize');
2852
+ $('winClose').innerHTML = svg('x');
2853
+ $('winMin').addEventListener('click', () => api.minimize());
2854
+ $('winMax').addEventListener('click', () => api.toggleMaximize());
2855
+ $('winClose').addEventListener('click', () => api.close());
2856
+ api.onMaximizeChange?.((maximized) => {
2857
+ $('winMax').innerHTML = svg(maximized ? 'restore' : 'maximize');
2858
+ $('winMax').title = maximized ? '还原' : '最大化';
2859
+ });
2860
+ }
2861
+
1725
2862
  function bind() {
1726
2863
  $('newChat').innerHTML = svg('plus');
1727
2864
  $('sendBtn').innerHTML = svg('send');
@@ -1729,8 +2866,15 @@ function bind() {
1729
2866
  $('toggleSidebar').innerHTML = svg('list');
1730
2867
  $('closeSettings').innerHTML = svg('x');
1731
2868
  $('filesBtn').innerHTML = svg('panel');
1732
- $('closeFiles').innerHTML = svg('x');
2869
+ $('changesBtn').innerHTML = svg('diff');
2870
+ $('wbClose').innerHTML = svg('x');
2871
+ $('pluginsBtn').innerHTML = svg('plug');
2872
+ initWorkbench();
2873
+ initFileResize();
1733
2874
  bindTerminal();
2875
+ initTooltips();
2876
+ initSelectionTools();
2877
+ initDesktop();
1734
2878
  hydrate();
1735
2879
  loadTheme();
1736
2880
 
@@ -1740,6 +2884,7 @@ function bind() {
1740
2884
  const result = await post('session', { action: 'new' });
1741
2885
  if (result?.info) state.info = result.info;
1742
2886
  if (result?.sessions) state.sessions = result.sessions;
2887
+ state.changes = null;
1743
2888
  renderHeader();
1744
2889
  renderSidebar();
1745
2890
  renderThread();
@@ -1749,8 +2894,8 @@ function bind() {
1749
2894
  }
1750
2895
  });
1751
2896
  $('abortBtn').addEventListener('click', async () => { controller?.abort(); await post('abort'); });
1752
- $('modelBtn').addEventListener('click', openSettings);
1753
- $('openSettings').addEventListener('click', openSettings);
2897
+ $('modelBtn').addEventListener('click', () => openSettings());
2898
+ $('openSettings').addEventListener('click', () => openSettings());
1754
2899
  $('closeSettings').addEventListener('click', closeSettings);
1755
2900
  $('settingsSheet').addEventListener('click', (event) => {
1756
2901
  if (event.target === $('settingsSheet')) closeSettings();
@@ -1760,8 +2905,21 @@ function bind() {
1760
2905
  });
1761
2906
  $('toggleSidebar').addEventListener('click', () => $('sidebar').classList.toggle('open'));
1762
2907
  $('filesBtn').addEventListener('click', toggleFiles);
2908
+ $('changesBtn').addEventListener('click', openChanges);
1763
2909
  $('themeBtn').addEventListener('click', cycleTheme);
1764
- $('closeFiles').addEventListener('click', () => { $('filesPanel').hidden = true; });
2910
+ $('pluginsBtn').addEventListener('click', () => openSettings('plugins'));
2911
+ $('previewWrap').addEventListener('click', toggleWrap);
2912
+ $('viewerWrap').addEventListener('click', toggleWrap);
2913
+ $('previewCopy').addEventListener('click', () => copyText(state.preview?.code ?? '', '已复制代码'));
2914
+ $('viewerCopy').addEventListener('click', () => copyText(state.preview?.code ?? '', '已复制代码'));
2915
+ $('previewCopyPath').addEventListener('click', () => copyText(state.preview?.path ?? '', '已复制路径'));
2916
+ $('viewerCopyPath').addEventListener('click', () => copyText(state.preview?.path ?? '', '已复制路径'));
2917
+ $('previewFull').addEventListener('click', openViewer);
2918
+ $('previewClose').addEventListener('click', closePreview);
2919
+ $('viewerClose').addEventListener('click', closeViewer);
2920
+ $('codeViewer').addEventListener('mousedown', (event) => {
2921
+ if (event.target === $('codeViewer')) closeViewer();
2922
+ });
1765
2923
  $('insertPath').addEventListener('click', () => {
1766
2924
  const path = $('insertPath').dataset.path;
1767
2925
  if (!path) return;
@@ -1777,6 +2935,8 @@ function bind() {
1777
2935
  $('undoBtn').addEventListener('click', async () => {
1778
2936
  const result = await post('undo');
1779
2937
  toast(result.had ? `已回滚:恢复 ${result.restored} 个文件` : '没有可回滚的改动');
2938
+ state.changes = null;
2939
+ if (state.workbench.open && state.workbench.tab === 'changes') void loadChanges(true);
1780
2940
  });
1781
2941
 
1782
2942
  $('composer').addEventListener('submit', (event) => { event.preventDefault(); send(); });
@@ -1813,12 +2973,40 @@ function bind() {
1813
2973
  if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); send(); }
1814
2974
  });
1815
2975
 
2976
+ $('ccInput').addEventListener('input', () => {
2977
+ state.ccIndex = 0;
2978
+ renderCommandCenter($('ccInput').value);
2979
+ scheduleCommandFiles($('ccInput').value);
2980
+ });
2981
+ $('ccInput').addEventListener('keydown', (event) => {
2982
+ if (event.key === 'ArrowDown') { event.preventDefault(); moveCommandCenter(1); }
2983
+ else if (event.key === 'ArrowUp') { event.preventDefault(); moveCommandCenter(-1); }
2984
+ else if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); runCommandCenterItem(state.ccItems?.[state.ccIndex]); }
2985
+ else if (event.key === 'Escape') { event.preventDefault(); closeCommandCenter(); }
2986
+ });
2987
+ $('commandCenter').addEventListener('mousedown', (event) => {
2988
+ if (event.target === $('commandCenter')) closeCommandCenter();
2989
+ });
2990
+
1816
2991
  document.addEventListener('keydown', (event) => {
2992
+ if ((event.ctrlKey || event.metaKey) && String(event.key).toLowerCase() === 'k') {
2993
+ event.preventDefault();
2994
+ if ($('commandCenter').hidden) openCommandCenter();
2995
+ else closeCommandCenter();
2996
+ return;
2997
+ }
2998
+ if ((event.ctrlKey || event.metaKey) && event.shiftKey) {
2999
+ const key = String(event.key).toLowerCase();
3000
+ if (key === 'f') { event.preventDefault(); openFiles(); return; }
3001
+ if (key === 'g') { event.preventDefault(); openChanges(); return; }
3002
+ }
1817
3003
  if (event.key === 'Escape') {
1818
- if (!$('approvalModal').hidden) closeApproval(false);
1819
- else if (!$('settingsSheet').hidden) closeSettings();
1820
- else if (!$('filesPanel').hidden) $('filesPanel').hidden = true;
1821
- else if ($('sidebar').classList.contains('open')) $('sidebar').classList.remove('open');
3004
+ if (!$('commandPalette').hidden) { closePalette(); return; }
3005
+ // 终端里的 Esc 属于 shell,不要把工作台一起关掉
3006
+ const inTerminal = event.target instanceof Element && event.target.closest('#terminalPanel');
3007
+ if (inTerminal && $('settingsSheet').hidden && $('codeViewer').hidden && $('commandCenter').hidden && $('approvalModal').hidden) return;
3008
+ if (closeTopOverlay()) return;
3009
+ if ($('sidebar').classList.contains('open')) $('sidebar').classList.remove('open');
1822
3010
  }
1823
3011
  });
1824
3012