openclacky 1.5.21 → 1.5.23

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.
Files changed (110) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +119 -0
  3. data/docs/secretary-prototype.md +286 -0
  4. data/lib/clacky/agent/session_serializer.rb +15 -11
  5. data/lib/clacky/agent.rb +58 -15
  6. data/lib/clacky/agent_config.rb +3 -1
  7. data/lib/clacky/agent_profile.rb +33 -6
  8. data/lib/clacky/billing/platform_billing.rb +9 -0
  9. data/lib/clacky/default_extensions/advisor/README.md +25 -0
  10. data/lib/clacky/default_extensions/advisor/README.zh.md +25 -0
  11. data/lib/clacky/default_extensions/advisor/ext.yml +1 -1
  12. data/lib/clacky/default_extensions/advisor/icon.svg +14 -0
  13. data/lib/clacky/default_extensions/coding/ext.yml +0 -1
  14. data/lib/clacky/default_extensions/computer-use/README.md +48 -0
  15. data/lib/clacky/default_extensions/computer-use/README.zh.md +48 -0
  16. data/lib/clacky/default_extensions/computer-use/ext.yml +1 -1
  17. data/lib/clacky/default_extensions/computer-use/icon.svg +16 -0
  18. data/lib/clacky/default_extensions/ext-studio/ext.yml +0 -1
  19. data/lib/clacky/default_extensions/general/ext.yml +0 -1
  20. data/lib/clacky/default_extensions/git/README.md +41 -0
  21. data/lib/clacky/default_extensions/git/README.zh.md +41 -0
  22. data/lib/clacky/default_extensions/git/ext.yml +1 -1
  23. data/lib/clacky/default_extensions/git/icon.svg +15 -0
  24. data/lib/clacky/default_extensions/git/panels/git/view.js +1960 -399
  25. data/lib/clacky/default_extensions/meeting/README.md +46 -0
  26. data/lib/clacky/default_extensions/meeting/README.zh.md +47 -0
  27. data/lib/clacky/default_extensions/meeting/ext.yml +1 -1
  28. data/lib/clacky/default_extensions/meeting/icon.svg +13 -0
  29. data/lib/clacky/default_extensions/preview/README.md +29 -0
  30. data/lib/clacky/default_extensions/preview/README.zh.md +29 -0
  31. data/lib/clacky/default_extensions/preview/ext.yml +1 -1
  32. data/lib/clacky/default_extensions/preview/icon.svg +13 -0
  33. data/lib/clacky/default_extensions/preview/panels/preview/view.js +199 -34
  34. data/lib/clacky/default_extensions/secretary/agents/secretary.md +41 -0
  35. data/lib/clacky/default_extensions/secretary/agents/worker.md +35 -0
  36. data/lib/clacky/default_extensions/secretary/api/handler.rb +8 -0
  37. data/lib/clacky/default_extensions/secretary/ext.yml +39 -0
  38. data/lib/clacky/default_extensions/secretary/panels/work/view.js +344 -0
  39. data/lib/clacky/default_extensions/secretary/tools/delegate_work.rb +37 -0
  40. data/lib/clacky/default_extensions/secretary/tools/manage_work.rb +22 -0
  41. data/lib/clacky/default_extensions/secretary/tools/yield_work.rb +35 -0
  42. data/lib/clacky/default_extensions/time_machine/README.md +32 -0
  43. data/lib/clacky/default_extensions/time_machine/README.zh.md +32 -0
  44. data/lib/clacky/default_extensions/time_machine/ext.yml +1 -1
  45. data/lib/clacky/default_extensions/time_machine/icon.svg +14 -0
  46. data/lib/clacky/default_skills/channel-manager/SKILL.md +79 -8
  47. data/lib/clacky/default_skills/channel-manager/discord_setup.rb +5 -1
  48. data/lib/clacky/default_skills/channel-manager/weixin_setup.rb +8 -1
  49. data/lib/clacky/default_skills/cron-task-creator/SKILL.md +183 -206
  50. data/lib/clacky/default_skills/cron-task-creator/evals/evals.json +45 -0
  51. data/lib/clacky/default_skills/media-gen/SKILL.md +17 -8
  52. data/lib/clacky/extension/api_extension.rb +10 -2
  53. data/lib/clacky/extension/loader.rb +2 -0
  54. data/lib/clacky/extension/verifier.rb +2 -2
  55. data/lib/clacky/locales/en.rb +14 -0
  56. data/lib/clacky/locales/zh.rb +14 -0
  57. data/lib/clacky/prompts/base.md +1 -1
  58. data/lib/clacky/providers.rb +68 -31
  59. data/lib/clacky/search_config.rb +33 -11
  60. data/lib/clacky/server/channel/adapters/base.rb +18 -0
  61. data/lib/clacky/server/channel/adapters/feishu/message_parser.rb +1 -0
  62. data/lib/clacky/server/channel/adapters/telegram/adapter.rb +1 -0
  63. data/lib/clacky/server/channel/channel_config.rb +185 -48
  64. data/lib/clacky/server/channel/channel_manager.rb +179 -66
  65. data/lib/clacky/server/git_panel.rb +362 -35
  66. data/lib/clacky/server/http_server.rb +530 -181
  67. data/lib/clacky/server/preview.rb +118 -17
  68. data/lib/clacky/server/scheduler.rb +211 -51
  69. data/lib/clacky/server/web_ui_controller.rb +35 -27
  70. data/lib/clacky/session_manager.rb +56 -6
  71. data/lib/clacky/tools/base.rb +7 -1
  72. data/lib/clacky/utils/file_processor.rb +20 -10
  73. data/lib/clacky/utils/mac_app_detector.rb +8 -7
  74. data/lib/clacky/utils/model_pricing.rb +60 -2
  75. data/lib/clacky/utils/windows_app_detector.rb +3 -1
  76. data/lib/clacky/version.rb +1 -1
  77. data/lib/clacky/web/app.css +1114 -205
  78. data/lib/clacky/web/app.js +143 -8
  79. data/lib/clacky/web/auth.js +1 -1
  80. data/lib/clacky/web/components/code-editor.js +73 -4
  81. data/lib/clacky/web/components/composer.js +107 -8
  82. data/lib/clacky/web/components/image-zoom.js +165 -0
  83. data/lib/clacky/web/components/model-picker.js +7 -5
  84. data/lib/clacky/web/components/notify.js +39 -12
  85. data/lib/clacky/web/components/onboard.js +1 -1
  86. data/lib/clacky/web/core/aside.js +60 -3
  87. data/lib/clacky/web/features/billing/view.js +2 -2
  88. data/lib/clacky/web/features/channels/store.js +19 -4
  89. data/lib/clacky/web/features/channels/view.js +92 -28
  90. data/lib/clacky/web/features/extensions/view.js +17 -10
  91. data/lib/clacky/web/features/new-session/store.js +79 -2
  92. data/lib/clacky/web/features/new-session/view.js +516 -75
  93. data/lib/clacky/web/features/skills/store.js +1 -1
  94. data/lib/clacky/web/features/tasks/store.js +5 -3
  95. data/lib/clacky/web/features/tasks/view.js +249 -66
  96. data/lib/clacky/web/features/workspace/store.js +13 -6
  97. data/lib/clacky/web/features/workspace/view.js +340 -214
  98. data/lib/clacky/web/i18n.js +366 -68
  99. data/lib/clacky/web/index.html +196 -165
  100. data/lib/clacky/web/projects.js +37 -4
  101. data/lib/clacky/web/sessions.js +263 -146
  102. data/lib/clacky/web/settings.js +241 -53
  103. data/lib/clacky/web/skills.js +2 -2
  104. data/lib/clacky/web/theme.js +17 -2
  105. data/lib/clacky/web/utils.js +234 -2
  106. data/lib/clacky/web/weixin-qr.html +2 -1
  107. data/lib/clacky/web/ws-dispatcher.js +14 -31
  108. data/lib/clacky/work/service.rb +542 -0
  109. data/lib/clacky/work/store.rb +57 -0
  110. metadata +31 -1
@@ -13,7 +13,7 @@ const NewSessionView = (() => {
13
13
  const $ = (id) => document.getElementById(id);
14
14
 
15
15
  let _initialized = false;
16
- let _modelsLoaded = false;
16
+ let _modelsPromise = null;
17
17
 
18
18
  let _agentName = "";
19
19
  let _agentNamePromise = null;
@@ -52,7 +52,7 @@ const NewSessionView = (() => {
52
52
  return a.description || "";
53
53
  }
54
54
 
55
- const LS_SEEN_AGENTS_KEY = "openclacky.newSession.seenAgents";
55
+ const LS_SEEN_AGENTS_KEY = "clacky-new-session-seen-agents";
56
56
 
57
57
  function _seenAgents() {
58
58
  try {
@@ -239,17 +239,24 @@ const NewSessionView = (() => {
239
239
  Composer.setPlaceholder(input, I18n.t("chat.input.placeholder"));
240
240
  }
241
241
 
242
- async function _populateModels() {
243
- if (_modelsLoaded) return;
244
- const models = await NewSessionStore.loadModels();
245
- _modelsLoaded = true;
246
-
247
- // Set default modelId in store if not already set
248
- if (!NewSessionStore.state.advanced.modelId) {
249
- const def = models.find((m) => m.type === "default") || models[0];
250
- if (def) NewSessionStore.updateAdvanced({ modelId: def.id || "" });
251
- }
252
- _renderContextBar();
242
+ // Models are re-fetched on every panel show: the settings page can add or
243
+ // delete rows while this page is hidden, and a cached list would keep
244
+ // offering the old set. Concurrent calls share one request.
245
+ function _populateModels() {
246
+ if (_modelsPromise) return _modelsPromise;
247
+ _modelsPromise = NewSessionStore.loadModels().then((models) => {
248
+ const adv = NewSessionStore.state.advanced;
249
+ const known = models.some((m) => (m.id || "") === adv.modelId);
250
+ // An empty list means the fetch failed, not that every model is gone —
251
+ // keep the current pick instead of clearing it on a network blip.
252
+ if (models.length && !known) {
253
+ const def = models.find((m) => m.type === "default") || models[0];
254
+ NewSessionStore.updateAdvanced({ modelId: def.id || "" });
255
+ }
256
+ _renderContextBar();
257
+ return models;
258
+ }).finally(() => { _modelsPromise = null; });
259
+ return _modelsPromise;
253
260
  }
254
261
 
255
262
  async function _prefillDefaultDir() {
@@ -356,20 +363,6 @@ const NewSessionView = (() => {
356
363
  const MAX_FILE_BYTES = 300 * 1024 * 1024;
357
364
  const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
358
365
 
359
- function _docTypeIcon(mimeType, filename) {
360
- const lower = (filename || "").toLowerCase();
361
- if (mimeType === "application/pdf" || lower.endsWith(".pdf")) return "📄";
362
- if (mimeType === "application/zip" || lower.endsWith(".zip")) return "🗜️";
363
- if (lower.endsWith(".tar") || lower.endsWith(".gz") || lower.endsWith(".tgz") ||
364
- lower.endsWith(".tar.gz") || lower.endsWith(".rar") || lower.endsWith(".7z")) return "🗜️";
365
- if ((mimeType && mimeType.includes("wordprocessingml")) || lower.endsWith(".doc") || lower.endsWith(".docx")) return "📝";
366
- if ((mimeType && mimeType.includes("spreadsheetml")) || lower.endsWith(".xls") || lower.endsWith(".xlsx")) return "📊";
367
- if ((mimeType && mimeType.includes("presentationml")) || lower.endsWith(".ppt") || lower.endsWith(".pptx")) return "📋";
368
- if (mimeType === "text/csv" || lower.endsWith(".csv")) return "📊";
369
- if (lower.endsWith(".md") || lower.endsWith(".markdown")) return "📝";
370
- return "📎";
371
- }
372
-
373
366
  function _compressImage(file) {
374
367
  return new Promise((resolve, reject) => {
375
368
  const reader = new FileReader();
@@ -477,7 +470,7 @@ const NewSessionView = (() => {
477
470
  const removeBtn = document.createElement("button");
478
471
  removeBtn.className = "img-preview-remove";
479
472
  removeBtn.textContent = "✕";
480
- removeBtn.title = "Remove";
473
+ removeBtn.title = I18n.t("tooltip.remove");
481
474
  removeBtn.addEventListener("click", () => { _pendingImages.splice(idx, 1); _renderAttachmentPreviews(); });
482
475
  item.appendChild(thumbnail);
483
476
  item.appendChild(removeBtn);
@@ -490,7 +483,7 @@ const NewSessionView = (() => {
490
483
  item.title = f.name;
491
484
  const icon = document.createElement("div");
492
485
  icon.className = "pdf-preview-icon";
493
- icon.textContent = _docTypeIcon(f.mime_type, f.name);
486
+ icon.innerHTML = Clacky.WorkspaceView.fileIcon(f.name);
494
487
  const info = document.createElement("div");
495
488
  info.className = "pdf-preview-info";
496
489
  const name = document.createElement("div");
@@ -504,7 +497,7 @@ const NewSessionView = (() => {
504
497
  const removeBtn = document.createElement("button");
505
498
  removeBtn.className = "pdf-preview-remove";
506
499
  removeBtn.textContent = "✕";
507
- removeBtn.title = "Remove";
500
+ removeBtn.title = I18n.t("tooltip.remove");
508
501
  removeBtn.addEventListener("click", () => { _pendingFiles.splice(idx, 1); _renderAttachmentPreviews(); });
509
502
  item.appendChild(icon);
510
503
  item.appendChild(info);
@@ -541,11 +534,15 @@ const NewSessionView = (() => {
541
534
  }
542
535
  if (_pendingFiles.length > 0) {
543
536
  const badges = _pendingFiles.map((f) => {
544
- const icon = _docTypeIcon(f.mime_type, f.name);
537
+ const icon = Clacky.WorkspaceView.fileIcon(f.name);
545
538
  const ext = (f.name.split(".").pop() || "file").toUpperCase();
546
- return `<span class="msg-pdf-badge"><span class="msg-pdf-badge-icon">${icon}</span>` +
539
+ const tag = f.path ? "button" : "span";
540
+ const attrs = f.path
541
+ ? ` type="button" class="msg-pdf-badge msg-file-open" data-file-path="${encodeURIComponent(f.path)}"`
542
+ : ` class="msg-pdf-badge"`;
543
+ return `<${tag}${attrs}><span class="msg-pdf-badge-icon">${icon}</span>` +
547
544
  `<span class="msg-pdf-badge-info"><span class="msg-pdf-badge-name">${escapeHtml(f.name)}</span>` +
548
- `<span class="msg-pdf-badge-type">${escapeHtml(ext)}</span></span></span>`;
545
+ `<span class="msg-pdf-badge-type">${escapeHtml(ext)}</span></span></${tag}>`;
549
546
  }).join(" ");
550
547
  html = badges + (html ? "<br>" + html : "");
551
548
  }
@@ -604,6 +601,11 @@ const NewSessionView = (() => {
604
601
  if (popRect.bottom > window.innerHeight - 8) {
605
602
  pop.style.top = `${rect.top - popRect.height - 6}px`;
606
603
  }
604
+ // Keep the popover inside the viewport when the anchor sits near the right
605
+ // edge (narrow windows), instead of letting it run off-screen.
606
+ if (popRect.right > window.innerWidth - 8) {
607
+ pop.style.left = `${Math.max(8, window.innerWidth - popRect.width - 8)}px`;
608
+ }
607
609
 
608
610
  const dismiss = (e) => {
609
611
  if (!pop.contains(e.target) && e.target !== anchor) {
@@ -799,36 +801,482 @@ const NewSessionView = (() => {
799
801
  _updateSendButton();
800
802
  }
801
803
 
804
+ // ── Branch chip popover — search, switch, create ──
805
+ // Branches live in the project's work tree, not in the session, so switching
806
+ // here really runs `git checkout` on the shared directory. Local branches
807
+ // switch directly; remote ones become a tracking branch of the same name.
808
+ function _openBranchPopover(anchor) {
809
+ const zh = _isZh();
810
+ const projectId = NewSessionStore.state.advanced.projectId;
811
+ if (!projectId) return;
812
+
813
+ let busy = false;
814
+
815
+ _showCtxPopover(anchor, (pop) => {
816
+ pop.classList.add("ns-branch-pop");
817
+
818
+ const header = document.createElement("div");
819
+ header.className = "ns-branch-search";
820
+ header.innerHTML =
821
+ '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
822
+ 'stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>';
823
+ const input = document.createElement("input");
824
+ input.type = "text";
825
+ input.className = "ns-branch-search-input";
826
+ input.placeholder = zh ? "搜索分支" : "Search branches";
827
+ input.autocomplete = "off";
828
+ input.spellcheck = false;
829
+ header.appendChild(input);
830
+ pop.appendChild(header);
831
+
832
+ const list = document.createElement("div");
833
+ list.className = "ns-branch-list";
834
+ pop.appendChild(list);
835
+
836
+ const foot = document.createElement("div");
837
+ foot.className = "ns-branch-foot";
838
+ pop.appendChild(foot);
839
+
840
+ const _showError = (msg) => {
841
+ Clacky.Modal.toast(msg, "error");
842
+ };
843
+
844
+ const _checkout = async (branch, opts = {}) => {
845
+ if (busy) return;
846
+ busy = true;
847
+ list.classList.add("is-busy");
848
+ try {
849
+ const data = await Projects.checkoutBranch(projectId, {
850
+ branch,
851
+ dir: NewSessionStore.state.advanced.workingDir || "",
852
+ ...opts,
853
+ });
854
+ NewSessionStore.applyGitState(data);
855
+ _dismissCtxPopover();
856
+ } catch (e) {
857
+ busy = false;
858
+ list.classList.remove("is-busy");
859
+ _showError(_branchErrorText(e.message, zh, branch));
860
+ }
861
+ };
862
+
863
+ const _branchItem = (b, label, onClick) => {
864
+ const item = document.createElement("button");
865
+ item.type = "button";
866
+ item.className = "ns-ctx-popover-item ns-branch-item" + (b.current ? " active" : "");
867
+ const icon =
868
+ '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
869
+ 'stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/>' +
870
+ '<circle cx="18" cy="8" r="2.5"/><path d="M6 8.5v7"/><path d="M18 10.5c0 3-2.5 4.5-6 5"/></svg>';
871
+ const check = b.current
872
+ ? '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" ' +
873
+ 'stroke-linecap="round" stroke-linejoin="round"><path d="m20 6-11 11-5-5"/></svg>'
874
+ : "";
875
+ item.innerHTML =
876
+ `<span class="ns-branch-item-icon">${icon}</span>` +
877
+ `<span class="ns-branch-item-label">${_escHtml(label)}</span>` +
878
+ `<span class="ns-branch-item-check">${check}</span>`;
879
+ item.title = label;
880
+ item.addEventListener("click", onClick);
881
+ return item;
882
+ };
883
+
884
+ const _localName = (ref) => ref.replace(/^[^/]+\//, "");
885
+
886
+ const renderList = () => {
887
+ const q = input.value.trim().toLowerCase();
888
+ const branches = NewSessionStore.state.git.branches || [];
889
+ const local = branches.filter(b => !b.remote && b.name.toLowerCase().includes(q));
890
+ const remote = branches.filter(b => b.remote && b.name.toLowerCase().includes(q));
891
+ const currentRef = NewSessionStore.state.git.branch;
892
+ const localNames = new Set(branches.filter(b => !b.remote).map(b => b.name));
893
+
894
+ list.innerHTML = "";
895
+ list.scrollTop = 0;
896
+
897
+ if (!local.length && !remote.length) {
898
+ const empty = document.createElement("div");
899
+ empty.className = "ns-ctx-popover-empty";
900
+ empty.textContent = q
901
+ ? (zh ? "没有匹配的分支" : "No matching branches")
902
+ : (zh ? "暂无分支" : "No branches");
903
+ list.appendChild(empty);
904
+ return;
905
+ }
906
+
907
+ const addGroup = (title, items, toItem) => {
908
+ if (!items.length) return;
909
+ const label = document.createElement("div");
910
+ label.className = "ns-branch-group";
911
+ label.textContent = title;
912
+ list.appendChild(label);
913
+ items.forEach(b => list.appendChild(toItem(b)));
914
+ };
915
+
916
+ addGroup(zh ? "分支" : "Branches", local, (b) => {
917
+ const isCurrent = b.name === currentRef || b.current;
918
+ return _branchItem({ current: isCurrent }, b.name, () => {
919
+ if (isCurrent) { _dismissCtxPopover(); return; }
920
+ _checkout(b.name);
921
+ });
922
+ });
923
+
924
+ addGroup(zh ? "远程" : "Remote", remote, (b) => {
925
+ // A remote ref is not a thing HEAD can point at, so picking one
926
+ // materialises a local branch of the same name (or reuses it).
927
+ const short = _localName(b.name);
928
+ const existsLocally = localNames.has(short);
929
+ const item = _branchItem({ current: false }, b.name, () => {
930
+ if (existsLocally) _checkout(short);
931
+ else _checkout(short, { create: true, from: b.name });
932
+ });
933
+ item.classList.add("is-remote");
934
+ return item;
935
+ });
936
+ };
937
+
938
+ // Naming a new branch needs room for the prefix rule and validation
939
+ // messages, so it opens in a modal instead of an inline field here.
940
+ const createBtn = document.createElement("button");
941
+ createBtn.type = "button";
942
+ createBtn.className = "ns-ctx-popover-item ns-branch-create";
943
+ createBtn.innerHTML =
944
+ '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
945
+ 'stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>' +
946
+ `<span>${zh ? "创建并检出分支…" : "Create and check out…"}</span>`;
947
+ createBtn.addEventListener("click", () => {
948
+ _dismissCtxPopover();
949
+ _openCreateBranchModal();
950
+ });
951
+ foot.appendChild(createBtn);
952
+
953
+ input.addEventListener("input", renderList);
954
+ input.addEventListener("keydown", (e) => {
955
+ if (e.key === "Escape") { e.preventDefault(); _dismissCtxPopover(); }
956
+ });
957
+
958
+ renderList();
959
+ setTimeout(() => input.focus(), 30);
960
+ });
961
+ }
962
+
963
+ // ── Create-branch modal ──
964
+ // Mirrors `git check-ref-format --branch` locally so most mistakes are caught
965
+ // before the round trip; git's own message is shown for anything missed.
966
+ function _branchNameError(name, zh) {
967
+ if (!name) return zh ? "请输入分支名称。" : "Please enter a branch name.";
968
+ if (name.endsWith("/")) return zh ? '分支名不能以"/"结尾。' : 'Branch name cannot end with "/".';
969
+ if (name.startsWith("/")) return zh ? '分支名不能以"/"开头。' : 'Branch name cannot start with "/".';
970
+ if (name.startsWith("-")) return zh ? '分支名不能以"-"开头。' : 'Branch name cannot start with "-".';
971
+ if (name.indexOf("//") !== -1) return zh ? '分支名不能包含"//"。' : 'Branch name cannot contain "//".';
972
+ if (name.indexOf("..") !== -1) return zh ? '分支名不能包含".."。' : 'Branch name cannot contain "..".';
973
+ if (name.endsWith(".")) return zh ? '分支名不能以"."结尾。' : 'Branch name cannot end with "."';
974
+ if (name.endsWith(".lock")) return zh ? '分支名不能以".lock"结尾。' : 'Branch name cannot end with ".lock".';
975
+ if (/[\s~^:?*\[\\\x00-\x1f\x7f]/.test(name)) {
976
+ return zh
977
+ ? "分支名不能包含空格或 ~ ^ : ? * [ \\ 等字符。"
978
+ : "Branch name cannot contain spaces or characters like ~ ^ : ? * [ \\.";
979
+ }
980
+ return "";
981
+ }
982
+
983
+ // git reports checkout failures on stderr in English and with a file list that
984
+ // would swamp the popover, so the common cases are rewritten for the active
985
+ // language; anything unrecognised is passed through untouched.
986
+ function _branchErrorText(raw, zh, branch, verb = "切换分支") {
987
+ const msg = String(raw || "").trim();
988
+ if (!zh) return msg || "Failed";
989
+ if (!msg) return `${verb}失败。`;
990
+
991
+ if (/local changes to the following files would be overwritten/i.test(msg)) {
992
+ const files = msg
993
+ .split("\n")
994
+ .filter(line => line.startsWith("\t"))
995
+ .map(line => line.trim())
996
+ .filter(Boolean);
997
+ if (!files.length) return "本地有未提交的修改,切换分支会被覆盖。请先提交或暂存后再试。";
998
+ const shown = files.slice(0, 5);
999
+ const more = files.length > shown.length ? `\n…(共 ${files.length} 个文件)` : "";
1000
+ return `本地有未提交的修改,切换分支会被覆盖:\n${shown.join("\n")}${more}\n请先提交或暂存后再试。`;
1001
+ }
1002
+ if (/untracked working tree files would be overwritten/i.test(msg)) {
1003
+ return "本地有未跟踪的文件会被覆盖,请先移走或提交后再试。";
1004
+ }
1005
+ if (/a branch named '.+' already exists/i.test(msg)) {
1006
+ const found = msg.match(/a branch named '(.+)' already exists/i);
1007
+ return `分支 ${found ? found[1] : branch || ""} 已存在。`;
1008
+ }
1009
+ if (/not a valid branch name/i.test(msg)) return "分支名不合法。";
1010
+ if (/couldn't find remote ref/i.test(msg)) return "远程分支不存在。";
1011
+ if (/did not match any file\(s\) known to git|pathspec .+ did not match/i.test(msg)) {
1012
+ return "找不到该分支。";
1013
+ }
1014
+ if (/not a git repository/i.test(msg)) return "该目录不是 Git 仓库。";
1015
+ if (/you need to resolve your current index first/i.test(msg)) {
1016
+ return "当前有未解决的合并冲突,请先处理后再切换分支。";
1017
+ }
1018
+ return `${verb}失败:${msg}`;
1019
+ }
1020
+
1021
+ function _openCreateBranchModal() {
1022
+ const zh = _isZh();
1023
+ const projectId = NewSessionStore.state.advanced.projectId;
1024
+ if (!projectId) return;
1025
+
1026
+ let prefix = "";
1027
+ let busy = false;
1028
+
1029
+ const overlay = document.createElement("div");
1030
+ overlay.className = "modal-overlay";
1031
+ overlay.innerHTML =
1032
+ '<div class="modal-box sm ns-branch-modal" role="dialog" aria-modal="true">' +
1033
+ '<div class="modal-header">' +
1034
+ `<h3 class="modal-title">${zh ? "创建并检出分支" : "Create and check out branch"}</h3>` +
1035
+ '<button type="button" class="modal-close-btn ns-branch-modal-close" aria-label="Close"></button>' +
1036
+ "</div>" +
1037
+ '<div class="modal-body">' +
1038
+ '<div class="modal-field">' +
1039
+ '<div class="ns-branch-field-head">' +
1040
+ `<span class="modal-label">${zh ? "分支名称" : "Branch name"}</span>` +
1041
+ `<button type="button" class="ns-branch-prefix-btn">${zh ? "设置前缀" : "Set prefix"}</button>` +
1042
+ "</div>" +
1043
+ '<div class="ns-branch-name-row">' +
1044
+ '<span class="ns-branch-prefix-chip" hidden></span>' +
1045
+ '<input type="text" class="ns-branch-name-input" autocomplete="off" spellcheck="false"' +
1046
+ ` aria-label="${zh ? "分支名称" : "Branch name"}"` +
1047
+ ` placeholder="${zh ? "例如 feature/login" : "e.g. feature/login"}">` +
1048
+ "</div>" +
1049
+ '<div class="ns-branch-modal-error" hidden></div>' +
1050
+ "</div>" +
1051
+ "</div>" +
1052
+ '<div class="modal-footer">' +
1053
+ `<button type="button" class="btn-secondary ns-branch-modal-cancel">${zh ? "关闭" : "Close"}</button>` +
1054
+ `<button type="button" class="btn-primary ns-branch-modal-submit">${zh ? "创建并检出" : "Create and check out"}</button>` +
1055
+ "</div>" +
1056
+ "</div>";
1057
+ document.body.appendChild(overlay);
1058
+
1059
+ const input = overlay.querySelector(".ns-branch-name-input");
1060
+ const prefixChip = overlay.querySelector(".ns-branch-prefix-chip");
1061
+ const prefixBtn = overlay.querySelector(".ns-branch-prefix-btn");
1062
+ const nameRow = overlay.querySelector(".ns-branch-name-row");
1063
+ const errorEl = overlay.querySelector(".ns-branch-modal-error");
1064
+ const submitBtn = overlay.querySelector(".ns-branch-modal-submit");
1065
+ const cancelBtn = overlay.querySelector(".ns-branch-modal-cancel");
1066
+ const closeBtn = overlay.querySelector(".ns-branch-modal-close");
1067
+
1068
+ const fullName = () => (prefix + input.value.trim()).trim();
1069
+
1070
+ const setError = (msg) => {
1071
+ errorEl.textContent = msg;
1072
+ errorEl.hidden = !msg;
1073
+ nameRow.classList.toggle("is-invalid", !!msg);
1074
+ };
1075
+
1076
+ const sync = () => {
1077
+ const name = input.value.trim();
1078
+ prefixChip.hidden = !prefix;
1079
+ prefixChip.textContent = prefix;
1080
+ prefixBtn.textContent = prefix
1081
+ ? (zh ? "取消前缀" : "Clear prefix")
1082
+ : (zh ? "设置前缀" : "Set prefix");
1083
+ prefixBtn.disabled = busy || (!prefix && !name);
1084
+ submitBtn.disabled = busy || !name;
1085
+ setError(name ? _branchNameError(fullName(), zh) : "");
1086
+ };
1087
+
1088
+ const close = () => {
1089
+ unbindEnter();
1090
+ document.removeEventListener("keydown", onKeydown);
1091
+ overlay.remove();
1092
+ };
1093
+
1094
+ const onKeydown = (e) => {
1095
+ if (e.key === "Escape") { e.preventDefault(); close(); }
1096
+ };
1097
+
1098
+ const submit = async () => {
1099
+ if (busy) return;
1100
+ const branch = fullName();
1101
+ const err = _branchNameError(branch, zh);
1102
+ if (err) { setError(err); input.focus(); return; }
1103
+
1104
+ busy = true;
1105
+ const label = submitBtn.textContent;
1106
+ submitBtn.textContent = zh ? "创建中…" : "Creating…";
1107
+ sync();
1108
+ try {
1109
+ const data = await Projects.checkoutBranch(projectId, {
1110
+ branch,
1111
+ create: true,
1112
+ dir: NewSessionStore.state.advanced.workingDir || "",
1113
+ });
1114
+ NewSessionStore.applyGitState(data);
1115
+ close();
1116
+ } catch (e) {
1117
+ busy = false;
1118
+ submitBtn.textContent = label;
1119
+ sync();
1120
+ setError(_branchErrorText(e.message, zh, branch, "创建分支"));
1121
+ }
1122
+ };
1123
+
1124
+ prefixBtn.addEventListener("click", () => {
1125
+ const name = input.value.trim();
1126
+ if (prefix) {
1127
+ input.value = prefix + name;
1128
+ prefix = "";
1129
+ } else {
1130
+ if (!name) return;
1131
+ const cut = name.lastIndexOf("/");
1132
+ if (cut > 0) {
1133
+ prefix = name.slice(0, cut + 1);
1134
+ input.value = name.slice(cut + 1);
1135
+ } else {
1136
+ prefix = name + "/";
1137
+ input.value = "";
1138
+ }
1139
+ }
1140
+ input.focus();
1141
+ sync();
1142
+ });
1143
+
1144
+ input.addEventListener("input", sync);
1145
+ overlay.addEventListener("mousedown", (e) => { if (e.target === overlay) close(); });
1146
+ submitBtn.addEventListener("click", submit);
1147
+ cancelBtn.addEventListener("click", close);
1148
+ closeBtn.addEventListener("click", close);
1149
+ document.addEventListener("keydown", onKeydown);
1150
+ const unbindEnter = IME.bindEnter(input, submit);
1151
+
1152
+ sync();
1153
+ setTimeout(() => input.focus(), 50);
1154
+ }
1155
+
802
1156
  // ── Render context bar ──
1157
+ // Chips are created once and updated in place. Rebuilding the row on every
1158
+ // store event made it flash during a project switch: the branch chip dropped
1159
+ // out until git info arrived, which shoved the model and init chips sideways,
1160
+ // and the row was repainted two or three times per switch.
1161
+ const CTX_CHIP_ORDER = ["name", "project", "dir", "branch", "model", "init"];
1162
+
1163
+ const _ctxSvg = (body) =>
1164
+ `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
1165
+
1166
+ const CTX_ICONS = {
1167
+ name: _ctxSvg(`<path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>`),
1168
+ project: _ctxSvg(`<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>`),
1169
+ dir: _ctxSvg(`<rect width="18" height="18" x="3" y="3" rx="2"/><path d="m7 11 2-2-2-2"/><path d="M11 13h4"/>`),
1170
+ branch: _ctxSvg(`<circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="8" r="2.5"/><path d="M6 8.5v7"/><path d="M18 10.5c0 3-2.5 4.5-6 5"/>`),
1171
+ model: _ctxSvg(`<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/>`),
1172
+ init: _ctxSvg(`<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>`),
1173
+ };
1174
+
1175
+ let _ctxChips = null;
1176
+
1177
+ function _setChipLabel(chip, label) {
1178
+ const text = chip.querySelector(".ns-ctx-chip-label");
1179
+ if (text && text.textContent !== label) text.textContent = label;
1180
+ }
1181
+
1182
+ function _setChipIcon(chip, icon, cacheKey) {
1183
+ if (!icon) return;
1184
+ if (cacheKey && chip.dataset.iconKey === cacheKey) return;
1185
+ const slot = chip.querySelector(".ns-ctx-chip-icon");
1186
+ if (slot) {
1187
+ if (icon instanceof Node) {
1188
+ slot.innerHTML = "";
1189
+ slot.appendChild(icon);
1190
+ slot.classList.add("ns-ctx-chip-icon--badge");
1191
+ } else if (slot.innerHTML !== icon) {
1192
+ slot.innerHTML = icon;
1193
+ slot.classList.remove("ns-ctx-chip-icon--badge");
1194
+ }
1195
+ }
1196
+ if (cacheKey) chip.dataset.iconKey = cacheKey;
1197
+ }
1198
+
1199
+ function _ensureCtxChips(bar) {
1200
+ if (_ctxChips && _ctxChips.name.parentElement === bar) return _ctxChips;
1201
+ bar.innerHTML = "";
1202
+ _ctxChips = {};
1203
+ CTX_CHIP_ORDER.forEach((role) => {
1204
+ const onClick = {
1205
+ name: _openNamePopover,
1206
+ project: _openProjectPopover,
1207
+ dir: _openDirPopover,
1208
+ branch: _openBranchPopover,
1209
+ model: _openModelPopover,
1210
+ init: _toggleInitProject,
1211
+ }[role];
1212
+ const chip = _makeChip(CTX_ICONS[role], "", onClick);
1213
+ chip.dataset.ctxRole = role;
1214
+ _ctxChips[role] = chip;
1215
+ bar.appendChild(chip);
1216
+ });
1217
+ _ctxChips.branch.id = "ns-chip-branch";
1218
+ return _ctxChips;
1219
+ }
1220
+
803
1221
  function _renderContextBar() {
804
1222
  const bar = $("ns-context-bar");
805
1223
  if (!bar) return;
806
- bar.innerHTML = "";
1224
+ const chips = _ensureCtxChips(bar);
807
1225
 
808
1226
  const zh = _isZh();
809
1227
  const agent = NewSessionStore.currentAgent();
810
1228
  const adv = NewSessionStore.state.advanced;
811
1229
 
1230
+ // Session name chip — leads the bar: naming the session is the first thing
1231
+ // people do here, and every other chip is a setting they rarely touch.
1232
+ const nameVal = adv.name || "";
1233
+ _setChipLabel(chips.name, nameVal || (zh ? "会话名称" : "Name"));
1234
+ chips.name.classList.toggle("ns-ctx-chip--muted", !nameVal);
1235
+
812
1236
  // Project chip
813
1237
  const projectId = adv.projectId;
814
1238
  const project = projectId && typeof Projects !== "undefined" && Projects.find
815
1239
  ? Projects.find(projectId)
816
1240
  : null;
817
- const projectLabel = project
818
- ? project.name
819
- : (zh ? "选择项目" : "Project");
820
- const projectIcon = `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>`;
821
- const projectChip = _makeChip(projectIcon, projectLabel, _openProjectPopover);
822
- if (!projectId) projectChip.classList.add("ns-ctx-chip--muted");
823
- bar.appendChild(projectChip);
824
-
825
- // Session name chip (2nd position)
826
- const nameVal = adv.name || "";
827
- const nameLabel = nameVal || (zh ? "会话名称" : "Name");
828
- const nameIcon = `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>`;
829
- const nameChip = _makeChip(nameIcon, nameLabel, _openNamePopover);
830
- if (!nameVal) nameChip.classList.add("ns-ctx-chip--muted");
831
- bar.appendChild(nameChip);
1241
+ _setChipLabel(chips.project, project ? project.name : (zh ? "选择项目" : "Project"));
1242
+ chips.project.classList.toggle("ns-ctx-chip--muted", !projectId);
1243
+
1244
+ // Working dir chip — a terminal, not a folder: the folder glyph is already
1245
+ // the project chip's, and two folders in a row read as the same thing.
1246
+ const dirVal = adv.workingDir || "";
1247
+ const dirShort = dirVal
1248
+ ? dirVal.replace(/^.*[\/]([^\/]+[\/][^\/]*)$/, "$1").replace(/^.*[\/]/, "").slice(-32)
1249
+ : "";
1250
+ _setChipLabel(chips.dir, dirShort || (zh ? "工作目录" : "Directory"));
1251
+ chips.dir.classList.toggle("ns-ctx-chip--muted", !dirVal);
1252
+
1253
+ // Branch chip — coding agent on a git-backed project. The work tree's
1254
+ // branch is shared state, and the session's working dir can point at a
1255
+ // different repo than the project's, so the key is project + dir.
1256
+ const showBranch = !!(agent && agent.id === "coding" && projectId);
1257
+ const git = NewSessionStore.state.git || {};
1258
+ const gitKey = showBranch ? NewSessionStore.gitKey(projectId, dirVal) : "";
1259
+ const gitKnown = showBranch && git.loaded && git.key === gitKey;
1260
+
1261
+ if (showBranch && !gitKnown && !git.loading) {
1262
+ NewSessionStore.loadGitInfo(projectId, { dir: dirVal });
1263
+ }
1264
+
1265
+ // Only a confirmed non-repo hides the chip; while loading it stays in place
1266
+ // so the chips after it don't shift.
1267
+ chips.branch.hidden = !showBranch || (gitKnown && !git.repo);
1268
+ if (showBranch) {
1269
+ // Keep the previous branch name while a switch is in flight — swapping in
1270
+ // a placeholder and then the real name reads as two separate flickers.
1271
+ const branchLabel = gitKnown
1272
+ ? (git.branch || (zh ? "分支" : "Branch"))
1273
+ : (chips.branch.querySelector(".ns-ctx-chip-label").textContent || (zh ? "分支" : "Branch"));
1274
+ _setChipLabel(chips.branch, branchLabel);
1275
+ chips.branch.classList.toggle("ns-ctx-chip--muted", !gitKnown || !git.branch);
1276
+ chips.branch.title = gitKnown
1277
+ ? (zh ? "切换或创建分支" : "Switch or create a branch")
1278
+ : (zh ? "正在读取分支…" : "Loading branch…");
1279
+ }
832
1280
 
833
1281
  // Model chip — show selected model name from store (strip prefix/suffix for brevity)
834
1282
  let modelLabel = zh ? "模型" : "Model";
@@ -842,29 +1290,19 @@ const NewSessionView = (() => {
842
1290
  modelLabel = modelRaw.length > 28 ? modelRaw.slice(0, 26) + "…" : modelRaw;
843
1291
  }
844
1292
  }
845
- const modelIcon = modelRaw && typeof ModelPicker !== "undefined"
846
- ? ModelPicker.vendorBadge(modelRaw)
847
- : `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`;
848
- bar.appendChild(_makeChip(modelIcon, modelLabel, _openModelPopover));
849
-
850
- // Working dir chip
851
- const dirVal = adv.workingDir || "";
852
- const dirShort = dirVal
853
- ? dirVal.replace(/^.*[\/]([^\/]+[\/][^\/]*)$/, "$1").replace(/^.*[\/]/, "").slice(-32)
854
- : (zh ? "工作目录" : "Directory");
855
- const dirIcon = `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></svg>`;
856
- const dirChip = _makeChip(dirIcon, dirShort || (zh ? "工作目录" : "Directory"), _openDirPopover);
857
- if (!dirVal) dirChip.classList.add("ns-ctx-chip--muted");
858
- bar.appendChild(dirChip);
1293
+ _setChipLabel(chips.model, modelLabel);
1294
+ _setChipIcon(
1295
+ chips.model,
1296
+ modelRaw && typeof ModelPicker !== "undefined" ? ModelPicker.vendorBadge(modelRaw) : CTX_ICONS.model,
1297
+ modelRaw || "default"
1298
+ );
859
1299
 
860
1300
  // Init project chip — only for coding agent
861
- if (agent && agent.id === "coding") {
862
- const active = NewSessionStore.state.advanced.initProject === true;
863
- const initLabel = zh ? "初始化项目" : "Init project";
864
- const initIcon = `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>`;
865
- const initChip = _makeChip(initIcon, initLabel, _toggleInitProject);
866
- if (active) initChip.classList.add("ns-ctx-chip--active");
867
- bar.appendChild(initChip);
1301
+ const showInit = !!(agent && agent.id === "coding");
1302
+ chips.init.hidden = !showInit;
1303
+ if (showInit) {
1304
+ _setChipLabel(chips.init, zh ? "初始化项目" : "Init project");
1305
+ chips.init.classList.toggle("ns-ctx-chip--active", adv.initProject === true);
868
1306
  }
869
1307
  }
870
1308
 
@@ -943,6 +1381,7 @@ const NewSessionView = (() => {
943
1381
  _renderContextBar();
944
1382
  });
945
1383
  NewSessionStore.on("newSession:creating", _updateSendButton);
1384
+ NewSessionStore.on("newSession:git-changed", _renderContextBar);
946
1385
 
947
1386
  const input = $("new-session-input");
948
1387
  if (input) {
@@ -1013,11 +1452,6 @@ const NewSessionView = (() => {
1013
1452
 
1014
1453
  const sendBtn = $("new-session-send");
1015
1454
  if (sendBtn) sendBtn.addEventListener("click", _submit);
1016
-
1017
- // Context bar: load models eagerly, then render chips. The working-dir
1018
- // prefill happens in onPanelShow() instead, so it runs after loadAgents()
1019
- // restores the remembered project from localStorage.
1020
- _populateModels().then(() => _renderContextBar());
1021
1455
  }
1022
1456
 
1023
1457
  async function onPanelShow(params) {
@@ -1031,6 +1465,13 @@ const NewSessionView = (() => {
1031
1465
  // projectId from localStorage, which decides whether the working dir is
1032
1466
  // prefilled from the project or from the global default.
1033
1467
  await _prefillDefaultDir();
1468
+ await _populateModels();
1469
+ // Another session may have switched the work tree's branch while this page
1470
+ // was hidden, so the cached value is refreshed on every show.
1471
+ await NewSessionStore.loadGitInfo(NewSessionStore.state.advanced.projectId, {
1472
+ dir: NewSessionStore.state.advanced.workingDir || "",
1473
+ force: true,
1474
+ });
1034
1475
  _renderContextBar();
1035
1476
  _updateSendButton();
1036
1477
  const input = $("new-session-input");