lithe-cli 0.1.12__tar.gz → 0.2.1__tar.gz

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 (41) hide show
  1. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/PKG-INFO +14 -6
  2. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/README.md +13 -5
  3. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/__init__.py +1 -1
  4. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/ttui.py +189 -2
  5. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/ttui_render.py +13 -2
  6. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/ttui_widgets.py +191 -1
  7. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/tui.py +7 -0
  8. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/workbench.py +104 -1
  9. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli.egg-info/PKG-INFO +14 -6
  10. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_ttui.py +176 -0
  11. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_workbench.py +78 -0
  12. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/LICENSE +0 -0
  13. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/__main__.py +0 -0
  14. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/agent.py +0 -0
  15. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/cli_parser.py +0 -0
  16. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/clipboard.py +0 -0
  17. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/commands.py +0 -0
  18. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/config.py +0 -0
  19. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/main.py +0 -0
  20. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/profiles.py +0 -0
  21. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/prompts.py +0 -0
  22. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/py.typed +0 -0
  23. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/sessions.py +0 -0
  24. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/setup.py +0 -0
  25. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli/ui.py +0 -0
  26. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli.egg-info/SOURCES.txt +0 -0
  27. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli.egg-info/dependency_links.txt +0 -0
  28. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli.egg-info/entry_points.txt +0 -0
  29. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli.egg-info/requires.txt +0 -0
  30. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/lithe_cli.egg-info/top_level.txt +0 -0
  31. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/pyproject.toml +0 -0
  32. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/setup.cfg +0 -0
  33. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_cli.py +0 -0
  34. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_cli_budget_steer.py +0 -0
  35. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_cli_clipboard.py +0 -0
  36. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_cli_guard.py +0 -0
  37. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_cli_sessions.py +0 -0
  38. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_cli_subagents.py +0 -0
  39. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_profiles.py +0 -0
  40. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_setup.py +0 -0
  41. {lithe_cli-0.1.12 → lithe_cli-0.2.1}/tests/test_tui_v2.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.12
3
+ Version: 0.2.1
4
4
  Summary: Command-line interface for the lithe agent kernel: chat, one-shot runs, undo, and run inspection.
5
5
  License: MIT License
6
6
 
@@ -158,7 +158,7 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
158
158
  ── done · steps 3 · tokens 2100 · cost 0.0042
159
159
  ```
160
160
 
161
- 修改已有文件时,助手优先调用 `edit_file` 或 `apply_patch` 做局部更新;只有新建文件或需要整体替换时才使用 `write_file`。工具调用界面只显示工具名、文件路径等摘要,文件写入/编辑的结果带 `+N -M 行` 的行数变化提示(lithe 0.9.10 起由内核统计)。
161
+ 修改已有文件时,助手优先调用 `edit_file` 或 `apply_patch` 做局部更新;只有新建文件或需要整体替换时才使用 `write_file`。工具调用界面只显示工具名、文件路径等摘要,文件写入/编辑的结果带 `+N -M 行` 的行数变化提示(lithe 0.1.0 起由内核统计)。
162
162
 
163
163
  `--stream` streams tokens as they generate; `-v` adds per-call
164
164
  usage/context gauges; `--max-steps` caps the tool loop;
@@ -181,7 +181,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
181
181
  工具/待办、用量:
182
182
 
183
183
  ```text
184
- lithe 0.9.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
184
+ lithe 0.2.1 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
185
185
  ╭──────────────────────────────────────╮╭──────────────────────────╮
186
186
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
187
187
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -189,19 +189,27 @@ the conversation; the right sidebar is five fixed sections — 会话(current
189
189
  │ 已完成。 ││ F3 切换 · /new 新建 │
190
190
  │ ││ ◆ 模型 │
191
191
  │ ││ zhipu · glm-4.6 │
192
+ │ ││ zai · chat · F7 端点 │
192
193
  │ ││ ◆ 会话用量 │
193
194
  │ ││ 输入 1,024 · 输出 216 │
194
195
  ╰──────────────────────────────────────╯╰──────────────────────────╯
195
196
  Tab 采纳 → /model /models /new
196
197
  lithe ❯ _
197
- ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · /help
198
+ ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · F7 端点 · /help
198
199
  ```
199
200
 
200
201
  **Switch without leaving the screen**: `F3` opens the session picker
201
202
  (`Enter` switch, `n` new, `d` delete, `r` rename), `F4` the model picker
202
203
  (grouped by profile; `Enter` switch, `s` save as the profile's default,
203
- `r` fetch `/models`), and `F5` the settings picker (`Enter` toggles a
204
- capability; see below). Switching away from a running session does **not**
204
+ `r` fetch `/models`), `F5` the settings picker (`Enter` toggles a
205
+ capability; see below), and `F7` the **endpoint manager** — every saved
206
+ profile with its `provider · transport` dialect, base_url and masked
207
+ key; `Enter` switches, `n` creates a profile right in the form (provider
208
+ type cycled with Enter, base_url defaulting to each preset's official
209
+ URL — overridable for custom routers, star-echoed API key), `e` edits
210
+ one, `p` swaps its provider type. A profile created in the form is
211
+ switched to on save; edits to the current profile apply to the next
212
+ turn. Switching away from a running session does **not**
205
213
  cancel it — its badge stays lit and the pane rebuilds from the store when
206
214
  you come back. Typing `/` shows matching commands above the prompt (`Tab`
207
215
  accepts; `/model`, `/profile`, `/set` complete their arguments too),
@@ -109,7 +109,7 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
109
109
  ── done · steps 3 · tokens 2100 · cost 0.0042
110
110
  ```
111
111
 
112
- 修改已有文件时,助手优先调用 `edit_file` 或 `apply_patch` 做局部更新;只有新建文件或需要整体替换时才使用 `write_file`。工具调用界面只显示工具名、文件路径等摘要,文件写入/编辑的结果带 `+N -M 行` 的行数变化提示(lithe 0.9.10 起由内核统计)。
112
+ 修改已有文件时,助手优先调用 `edit_file` 或 `apply_patch` 做局部更新;只有新建文件或需要整体替换时才使用 `write_file`。工具调用界面只显示工具名、文件路径等摘要,文件写入/编辑的结果带 `+N -M 行` 的行数变化提示(lithe 0.1.0 起由内核统计)。
113
113
 
114
114
  `--stream` streams tokens as they generate; `-v` adds per-call
115
115
  usage/context gauges; `--max-steps` caps the tool loop;
@@ -132,7 +132,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
132
132
  工具/待办、用量:
133
133
 
134
134
  ```text
135
- lithe 0.9.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
135
+ lithe 0.2.1 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
136
136
  ╭──────────────────────────────────────╮╭──────────────────────────╮
137
137
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
138
138
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -140,19 +140,27 @@ the conversation; the right sidebar is five fixed sections — 会话(current
140
140
  │ 已完成。 ││ F3 切换 · /new 新建 │
141
141
  │ ││ ◆ 模型 │
142
142
  │ ││ zhipu · glm-4.6 │
143
+ │ ││ zai · chat · F7 端点 │
143
144
  │ ││ ◆ 会话用量 │
144
145
  │ ││ 输入 1,024 · 输出 216 │
145
146
  ╰──────────────────────────────────────╯╰──────────────────────────╯
146
147
  Tab 采纳 → /model /models /new
147
148
  lithe ❯ _
148
- ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · /help
149
+ ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · F7 端点 · /help
149
150
  ```
150
151
 
151
152
  **Switch without leaving the screen**: `F3` opens the session picker
152
153
  (`Enter` switch, `n` new, `d` delete, `r` rename), `F4` the model picker
153
154
  (grouped by profile; `Enter` switch, `s` save as the profile's default,
154
- `r` fetch `/models`), and `F5` the settings picker (`Enter` toggles a
155
- capability; see below). Switching away from a running session does **not**
155
+ `r` fetch `/models`), `F5` the settings picker (`Enter` toggles a
156
+ capability; see below), and `F7` the **endpoint manager** — every saved
157
+ profile with its `provider · transport` dialect, base_url and masked
158
+ key; `Enter` switches, `n` creates a profile right in the form (provider
159
+ type cycled with Enter, base_url defaulting to each preset's official
160
+ URL — overridable for custom routers, star-echoed API key), `e` edits
161
+ one, `p` swaps its provider type. A profile created in the form is
162
+ switched to on save; edits to the current profile apply to the next
163
+ turn. Switching away from a running session does **not**
156
164
  cancel it — its badge stays lit and the pane rebuilds from the store when
157
165
  you come back. Typing `/` shows matching commands above the prompt (`Tab`
158
166
  accepts; `/model`, `/profile`, `/set` complete their arguments too),
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.1.12"
3
+ __version__ = "0.2.1"
@@ -46,8 +46,9 @@ from .tui import (
46
46
  from .ui import fmt_duration as fmt_duration # noqa: F401 — legacy re-export
47
47
  from . import ttui_widgets as _widgets
48
48
  from .ttui_widgets import (
49
- ConfirmModal, ConversationPane, HistoryInput, PickerModal, SubagentCard,
50
- HistoryInputSubmitted, WbEvent, completion_suggestions, selected_text,
49
+ ConfirmModal, ConversationPane, FormModal, HistoryInput, PickerModal,
50
+ SubagentCard, HistoryInputSubmitted, WbEvent, completion_suggestions,
51
+ selected_text,
51
52
  )
52
53
  from .ttui_render import footer_text, header_text, sidebar_markup
53
54
 
@@ -79,6 +80,13 @@ class LitheApp(App):
79
80
  #picker-list { height: auto; max-height: 16; }
80
81
  #picker-hint { color: #94a3b8; }
81
82
  #picker-command { color: #f87171; }
83
+ #form-fields { height: auto; }
84
+ .form-row { height: 3; margin: 0 0 1 0; }
85
+ .form-row Label { width: 11; padding: 0 1 0 0; color: #94a3b8; }
86
+ .form-row Input { width: 1fr; }
87
+ Button.form-choice { width: 1fr; height: 3; border: round #334155;
88
+ background: #0f172a; color: #e2e8f0; padding: 0 1;
89
+ min-width: 0; content-align: left middle; }
82
90
  .user { color: #60a5fa; }
83
91
  .assistant { color: #4ade80; }
84
92
  .tool { color: #22d3ee; }
@@ -95,6 +103,7 @@ class LitheApp(App):
95
103
  Binding("f4", "open_model", "模型", priority=True),
96
104
  Binding("f5", "open_set", "设置", priority=True),
97
105
  Binding("f6", "open_reasoning", "推理", priority=True),
106
+ Binding("f7", "open_endpoint", "端点", priority=True),
98
107
  Binding("ctrl+c", "cancel_or_exit", "取消/退出", priority=True),
99
108
  ]
100
109
 
@@ -198,8 +207,25 @@ class LitheApp(App):
198
207
  )
199
208
  st.max_cost = self.cfg.max_cost
200
209
  st.max_total_tokens = self.cfg.max_total_tokens
210
+ self._sync_endpoint_view(st)
201
211
  return st
202
212
 
213
+ def _sync_endpoint_view(self, st: TuiState) -> None:
214
+ """Endpoint display fields for the sidebar's 模型 section."""
215
+ st.provider = self.cfg.provider or ""
216
+ st.temperature = self.cfg.temperature
217
+ st.max_output = self.cfg.max_tokens
218
+ st.dialect = ""
219
+ if self.cfg.profile:
220
+ try:
221
+ ep = self.wb.profiles.endpoint(self.cfg.profile)
222
+ except SystemExit:
223
+ ep = {}
224
+ st.dialect = self.wb._endpoint_dialect(ep)
225
+ elif st.provider:
226
+ st.dialect = self.wb._endpoint_dialect(
227
+ {"provider": st.provider})
228
+
203
229
  def _load_session_history(self, state: TuiState, cid: int) -> None:
204
230
  """Load both the orchestrator feed and subagent cards on first open.
205
231
 
@@ -241,6 +267,7 @@ class LitheApp(App):
241
267
  st.max_steps = self.cfg.max_steps
242
268
  st.max_cost = self.cfg.max_cost
243
269
  st.max_total_tokens = self.cfg.max_total_tokens
270
+ self._sync_endpoint_view(st)
244
271
  if self.wb.current is not None:
245
272
  st.session_id = self.wb.current["id"]
246
273
  st.session_title = self.wb.current.get("title") or ""
@@ -631,6 +658,38 @@ class LitheApp(App):
631
658
  "Enter 应用 · s 存为档案默认 · Esc 关闭",
632
659
  letter_actions={"s": "_picker_save_reasoning"},
633
660
  ), self._reasoning_picked)
661
+ elif name == "endpoint":
662
+ from .profiles import masked_key
663
+ from .ui import truncate
664
+
665
+ items = []
666
+ current = self.cfg.profile
667
+ for pname in self.wb.profiles.names():
668
+ try:
669
+ ep = self.wb.profiles.endpoint(pname)
670
+ except SystemExit:
671
+ continue
672
+ mark = "[green]●[/]" if pname == current else " "
673
+ dialect = self.wb._endpoint_dialect(ep) or "手写端点"
674
+ url = truncate(ep.get("base_url") or "(preset 补齐)", 34)
675
+ key = masked_key(ep.get("api_key") or "")
676
+ items.append((
677
+ {"profile": pname},
678
+ f"{mark} {pname} · {ep.get('model') or '—'}\n"
679
+ f" [dim]{dialect} · {url} · key {key}[/]",
680
+ ))
681
+ if not items:
682
+ items.append((
683
+ {"kind": "head"},
684
+ "[dim](没有已保存档案;n 新建)[/]",
685
+ ))
686
+ self.push_screen(PickerModal(
687
+ "端点档案", items,
688
+ "Enter 切换 · n 新建 · e 编辑 · p 改 provider · Esc 关闭",
689
+ letter_actions={"n": "_picker_new_profile",
690
+ "e": "_picker_edit_profile",
691
+ "p": "_picker_profile_provider"},
692
+ ), self._endpoint_picked)
634
693
 
635
694
  def action_open_sessions(self) -> None:
636
695
  if self.mode == "chat" and not isinstance(self.screen, PickerModal):
@@ -648,6 +707,134 @@ class LitheApp(App):
648
707
  if not isinstance(self.screen, PickerModal):
649
708
  self._open_picker("reasoning")
650
709
 
710
+ def action_open_endpoint(self) -> None:
711
+ if not isinstance(self.screen, PickerModal):
712
+ self._open_picker("endpoint")
713
+
714
+ def _endpoint_picked(self, result) -> None:
715
+ if not result:
716
+ return
717
+ kind = result[0]
718
+ if kind == "letter" and result[1]:
719
+ getattr(self, result[1])(result[2])
720
+ return
721
+ if kind != "select" or not result[1]:
722
+ return
723
+ payload = result[1]
724
+ if payload.get("kind") == "head":
725
+ return
726
+ r = self.wb.set_profile(payload["profile"])
727
+ for cls, text in r.messages:
728
+ self.state.say(cls, text)
729
+ self._refresh_meta()
730
+ self._refresh_chrome()
731
+ self._sync_feed()
732
+
733
+ # F7 表单:新建/编辑档案
734
+ def _picker_new_profile(self, payload) -> None:
735
+ self._open_profile_form(None)
736
+
737
+ def _picker_edit_profile(self, payload) -> None:
738
+ name = (payload or {}).get("profile")
739
+ self._open_profile_form(name)
740
+
741
+ def _open_profile_form(self, edit_name: str | None) -> None:
742
+ try:
743
+ from lithe.bundles.providers import PRESETS, known_providers
744
+ except ImportError:
745
+ PRESETS, known_providers = {}, []
746
+ provider_choices = ["none", *known_providers()]
747
+ preset_urls = {n: p.get("base_url") or ""
748
+ for n, p in PRESETS.items()}
749
+ ep: dict = {}
750
+ if edit_name:
751
+ try:
752
+ ep = self.wb.profiles.endpoint(edit_name)
753
+ except SystemExit:
754
+ ep = {}
755
+
756
+ def _on_change(field: str, value: str) -> None:
757
+ if field != "provider":
758
+ return
759
+ # provider 换档时:base_url 为空或恰好是另一 preset 的官方
760
+ # URL → 跟着换成新 preset 的;用户手写的路由不动。
761
+ try:
762
+ form = self.screen
763
+ if not isinstance(form, FormModal):
764
+ return
765
+ current = form.values().get("base_url") or ""
766
+ if current and current not in preset_urls.values():
767
+ return
768
+ form.set_value("base_url", preset_urls.get(value, ""))
769
+ except Exception:
770
+ pass
771
+
772
+ fields = [
773
+ {"name": "profile", "label": "档案名",
774
+ "kind": "text", "default": edit_name or "",
775
+ "placeholder": "如 zhipu / my-router"},
776
+ {"name": "provider", "label": "Provider", "kind": "choice",
777
+ "choices": provider_choices,
778
+ "default": ep.get("provider") or "none"},
779
+ {"name": "base_url", "label": "Base URL",
780
+ "kind": "text", "default": ep.get("base_url") or "",
781
+ "placeholder": "自建路由填自己的 URL"},
782
+ {"name": "api_key", "label": "API key",
783
+ "kind": "password", "default": ep.get("api_key") or ""},
784
+ {"name": "model", "label": "模型",
785
+ "kind": "text", "default": ep.get("model") or "",
786
+ "placeholder": "如 glm-4.6 / claude-sonnet-4"},
787
+ ]
788
+ self.push_screen(FormModal(
789
+ "新建端点档案" if not edit_name else f"编辑档案 {edit_name}",
790
+ fields,
791
+ "Enter 下一项(末项保存)· Provider 行 Enter 换选项 · Esc 取消"
792
+ " · provider=none 时 base_url 自填",
793
+ on_change=_on_change,
794
+ ), self._profile_form_saved)
795
+
796
+ def _profile_form_saved(self, result) -> None:
797
+ if not result or result[0] != "submit":
798
+ return
799
+ v = result[1]
800
+ r = self.wb.save_profile(
801
+ v.get("profile", ""), v.get("provider", ""),
802
+ v.get("base_url", ""), v.get("api_key", ""),
803
+ v.get("model", ""))
804
+ for cls, text in r.messages:
805
+ self.state.say(cls, text)
806
+ self._refresh_meta()
807
+ self._refresh_chrome()
808
+ self._sync_feed()
809
+
810
+ # F7 › p:快改 provider 类型
811
+ def _picker_profile_provider(self, payload) -> None:
812
+ name = (payload or {}).get("profile")
813
+ if not name:
814
+ return
815
+ try:
816
+ from lithe.bundles.providers import known_providers
817
+ except ImportError:
818
+ known_providers = []
819
+ items = []
820
+ for choice in ["none", *known_providers()]:
821
+ label = "none(手写端点)" if choice == "none" else choice
822
+ items.append(({"provider": choice}, f" {label}"))
823
+ self.push_screen(PickerModal(
824
+ f"{name} 的 provider 类型", items,
825
+ "Enter 应用 · Esc 取消",
826
+ ), lambda r: self._provider_choice_picked(name, r))
827
+
828
+ def _provider_choice_picked(self, name: str, result) -> None:
829
+ if not result or result[0] != "select" or not result[1]:
830
+ return
831
+ r = self.wb.change_profile_provider(name, result[1]["provider"])
832
+ for cls, text in r.messages:
833
+ self.state.say(cls, text)
834
+ self._refresh_meta()
835
+ self._refresh_chrome()
836
+ self._sync_feed()
837
+
651
838
  def _reasoning_picked(self, result) -> None:
652
839
  if not result or result[0] != "select" or not result[1]:
653
840
  return
@@ -41,8 +41,19 @@ def sidebar_markup(state: TuiState) -> str:
41
41
  out.append("[dim]◆ 模型[/]")
42
42
  label = f"{state.profile} · {state.model}" if state.profile else state.model
43
43
  out.append(f"[cyan]{label}[/]")
44
+ if state.dialect:
45
+ out.append(f"[dim]{state.dialect} · F7 端点[/]")
46
+ else:
47
+ out.append("[dim]F7 端点管理[/]")
44
48
  if state.reasoning_effort:
45
49
  out.append(f"[dim]推理 {state.reasoning_effort} · F6 切换[/]")
50
+ sampling = []
51
+ if state.temperature is not None:
52
+ sampling.append(f"温度 {state.temperature:g}")
53
+ if state.max_output:
54
+ sampling.append(f"输出上限 {state.max_output:,}")
55
+ if sampling:
56
+ out.append(f"[dim]{' · '.join(sampling)} · /set 调整[/]")
46
57
  if state.context_window:
47
58
  out.append(f"[dim]窗口 {state.context_window:,} · F4 切换[/]")
48
59
  else:
@@ -117,7 +128,7 @@ def footer_text(state: TuiState) -> str:
117
128
  live = state.elapsed()
118
129
  timer = f" · {fmt_duration(live)}" if live is not None else ""
119
130
  return (f" ● {state.status}{timer} · Ctrl+C 取消 · F3 会话"
120
- f" · F4 模型 · F6 推理 ")
131
+ f" · F4 模型 · F6 推理 · F7 端点 ")
121
132
  return (f" ● {state.status} · Enter 发送 · Ctrl+Enter 换行 · F2 侧栏"
122
133
  f" · F3 会话 · F4 模型"
123
- f" · F5 设置 · F6 推理 · /help ")
134
+ f" · F5 设置 · F6 推理 · F7 端点 · /help ")
@@ -7,7 +7,7 @@ from typing import Any
7
7
  from rich.text import Text
8
8
  from textual.app import ComposeResult
9
9
  from textual.binding import Binding
10
- from textual.containers import Vertical, VerticalScroll
10
+ from textual.containers import Horizontal, Vertical, VerticalScroll
11
11
  from textual.content import Content
12
12
  from textual.css.query import NoMatches
13
13
  from textual.message import Message
@@ -432,6 +432,196 @@ class PickerModal(ModalScreen):
432
432
  row.children[0].update(label)
433
433
 
434
434
 
435
+ # -- forms ------------------------------------------------------------------------
436
+
437
+ class FormModal(ModalScreen):
438
+ """A labeled-field form modal (the endpoint editor behind F7).
439
+
440
+ Fields are dicts: ``{"name", "label", "kind": "text" | "password" |
441
+ "choice", "default", "placeholder", "choices"}``. Enter advances to
442
+ the next field and submits on the last; choice fields cycle their
443
+ options on Enter or Space; Tab / ↑ / ↓ move between fields; Esc or
444
+ q cancels. ``on_change(field_name, value)`` fires after every value
445
+ change so the host can react (the provider field re-defaults
446
+ base_url to the chosen preset's official URL). Dismissals:
447
+ ``("submit", values-dict)`` or ``None``.
448
+ """
449
+
450
+ BINDINGS = [
451
+ Binding("escape", "cancel", "取消"),
452
+ Binding("q", "cancel", "取消", show=False),
453
+ Binding("down", "next_field", show=False, priority=True),
454
+ Binding("up", "prev_field", show=False, priority=True),
455
+ # Enter is owned by the form, not the widgets: Button's own
456
+ # two-phase key activation is version-flaky (press every other
457
+ # key in some builds), so one priority binding dispatches —
458
+ # choice rows cycle, text rows advance / submit. Mouse clicks
459
+ # keep the Button.Pressed path.
460
+ Binding("enter", "enter_key", show=False, priority=True),
461
+ ]
462
+
463
+ def __init__(self, title: str, fields: list[dict], hint: str = "",
464
+ on_change: Callable[[str, str], None] | None = None):
465
+ super().__init__()
466
+ self.title = title
467
+ self.fields = fields
468
+ self.hint = hint
469
+ self.on_change = on_change
470
+ self._values: dict[str, str] = {
471
+ f["name"]: str(f.get("default") or "") for f in fields}
472
+ self._choices: dict[str, list[str]] = {
473
+ f["name"]: list(f.get("choices") or [])
474
+ for f in fields if f.get("kind") == "choice"}
475
+
476
+ def compose(self) -> ComposeResult:
477
+ with Vertical(id="picker"):
478
+ yield Static(self.title, id="picker-title")
479
+ with Vertical(id="form-fields"):
480
+ for f in self.fields:
481
+ with Horizontal(classes="form-row"):
482
+ yield Label(f["label"], classes="form-label")
483
+ if f.get("kind") == "choice":
484
+ yield Button("", classes="form-choice",
485
+ id=f"form-{f['name']}")
486
+ else:
487
+ yield Input(
488
+ value=self._values[f["name"]],
489
+ placeholder=f.get("placeholder") or "",
490
+ password=f.get("kind") == "password",
491
+ id=f"form-{f['name']}",
492
+ )
493
+ yield Static(self.hint, id="picker-hint")
494
+
495
+ def on_mount(self) -> None:
496
+ self._sync_choice_buttons()
497
+ if self.fields:
498
+ self._focus(0)
499
+
500
+ # -- field plumbing ---------------------------------------------------------
501
+
502
+ def _field_index(self, widget_id: str | None) -> int | None:
503
+ if not widget_id:
504
+ return None
505
+ for i, f in enumerate(self.fields):
506
+ if f"form-{f['name']}" == widget_id:
507
+ return i
508
+ return None
509
+
510
+ def _focus(self, index: int) -> None:
511
+ f = self.fields[index]
512
+ self.query_one(f"#form-{f['name']}").focus()
513
+
514
+ def _sync_choice_buttons(self) -> None:
515
+ for f in self.fields:
516
+ if f.get("kind") != "choice":
517
+ continue
518
+ btn = self.query_one(f"#form-{f['name']}", Button)
519
+ value = self._values[f["name"]]
520
+ btn.label = f"{value} ▸" if value else "(空)"
521
+
522
+ def _changed(self, name: str, value: str) -> None:
523
+ if self.on_change is not None:
524
+ try:
525
+ self.on_change(name, value)
526
+ except Exception: # noqa: BLE001 — host callbacks must not kill the form
527
+ pass
528
+
529
+ def set_value(self, name: str, value: str) -> None:
530
+ """Host-side field update (e.g. re-default base_url) — text fields."""
531
+ f = next((x for x in self.fields if x["name"] == name), None)
532
+ if f is None or f.get("kind") == "choice":
533
+ return
534
+ self._values[name] = value
535
+ try:
536
+ self.query_one(f"#form-{name}", Input).value = value
537
+ except NoMatches:
538
+ pass
539
+
540
+ def values(self) -> dict[str, str]:
541
+ return dict(self._values)
542
+
543
+ # -- events ------------------------------------------------------------------
544
+
545
+ def on_input_submitted(self, event: Input.Submitted) -> None:
546
+ idx = self._field_index(event.input.id)
547
+ if idx is None:
548
+ return
549
+ name = self.fields[idx]["name"]
550
+ self._values[name] = event.value
551
+ self._changed(name, event.value)
552
+ if idx >= len(self.fields) - 1:
553
+ self.action_submit()
554
+ else:
555
+ self._focus(idx + 1)
556
+
557
+ def on_input_changed(self, event: Input.Changed) -> None:
558
+ idx = self._field_index(event.input.id)
559
+ if idx is not None:
560
+ self._values[self.fields[idx]["name"]] = event.value
561
+
562
+ def on_button_pressed(self, event: Button.Pressed) -> None:
563
+ """Mouse path for choice rows (keyboard goes through
564
+ :meth:`action_enter_key`)."""
565
+ idx = self._field_index(event.button.id)
566
+ if idx is None or self.fields[idx].get("kind") != "choice":
567
+ return
568
+ self._cycle_choice(self.fields[idx])
569
+
570
+ def _cycle_choice(self, field: dict) -> None:
571
+ opts = self._choices[field["name"]]
572
+ cur = self._values[field["name"]]
573
+ if not opts:
574
+ return
575
+ nxt = opts[(opts.index(cur) + 1) % len(opts)] if cur in opts \
576
+ else opts[0]
577
+ self._values[field["name"]] = nxt
578
+ self._sync_choice_buttons()
579
+ self._changed(field["name"], nxt)
580
+
581
+ # -- actions -------------------------------------------------------------------
582
+
583
+ def action_enter_key(self) -> None:
584
+ """One Enter, dispatched by field kind (see BINDINGS note)."""
585
+ idx = self._field_index(self.focused.id if self.focused else None)
586
+ if idx is None:
587
+ return
588
+ field = self.fields[idx]
589
+ if field.get("kind") == "choice":
590
+ self._cycle_choice(field)
591
+ return
592
+ value = getattr(self.focused, "value", "") or ""
593
+ self._values[field["name"]] = value
594
+ self._changed(field["name"], value)
595
+ if idx >= len(self.fields) - 1:
596
+ self.action_submit()
597
+ else:
598
+ self._focus(idx + 1)
599
+
600
+ def action_next_field(self) -> None:
601
+ idx = self._field_index(self.focused.id if self.focused else None)
602
+ if idx is not None and idx < len(self.fields) - 1:
603
+ self._focus(idx + 1)
604
+
605
+ def action_prev_field(self) -> None:
606
+ idx = self._field_index(self.focused.id if self.focused else None)
607
+ if idx is not None and idx > 0:
608
+ self._focus(idx - 1)
609
+
610
+ def action_submit(self) -> None:
611
+ # stop at the first blank required field: the hint names it
612
+ missing = [f["label"] for f in self.fields
613
+ if f.get("kind") != "choice" and f.get("required", True)
614
+ and not (self._values.get(f["name"]) or "").strip()]
615
+ if missing:
616
+ self.query_one("#picker-hint", Static).update(
617
+ f"还需填写:{'、'.join(missing)}(Esc 取消)")
618
+ return
619
+ self.dismiss(("submit", self.values()))
620
+
621
+ def action_cancel(self) -> None:
622
+ self.dismiss(None)
623
+
624
+
435
625
  # -- command approval --------------------------------------------------------
436
626
 
437
627
  class ConfirmModal(ModalScreen):
@@ -94,6 +94,13 @@ class TuiState:
94
94
  self.context_window = None
95
95
  self.context_percent = None
96
96
  self.reasoning_effort: str | None = None
97
+ # Endpoint view for the sidebar's 模型 section (provider preset,
98
+ # "provider · transport" dialect label, sampling knobs). Set by the
99
+ # TUI; the plain REPL renders no sidebar.
100
+ self.provider = ""
101
+ self.dialect = ""
102
+ self.temperature: float | None = None
103
+ self.max_output: int | None = None
97
104
  # Run budgets (for the sidebar progress lines); None = no cap.
98
105
  self.max_cost: float | None = None
99
106
  self.max_total_tokens: int | None = None
@@ -173,7 +173,22 @@ class Workbench:
173
173
  if "api_key" not in pinned:
174
174
  self.cfg.api_key = endpoint.get("api_key")
175
175
  if "base_url" not in pinned:
176
- self.cfg.base_url = endpoint.get("base_url")
176
+ base = endpoint.get("base_url")
177
+ if not base and endpoint.get("provider"):
178
+ # a preset-only profile stores an empty base_url; the
179
+ # preset's official URL fills it at adopt time, matching
180
+ # load_config's layering (switching must not blank the
181
+ # endpoint the way a raw copy would).
182
+ try:
183
+ from lithe.bundles.providers import get_preset
184
+ except ImportError:
185
+ get_preset = None
186
+ if get_preset is not None:
187
+ try:
188
+ base = get_preset(endpoint["provider"]).get("base_url")
189
+ except ValueError:
190
+ base = None
191
+ self.cfg.base_url = base
177
192
  if endpoint.get("model") and "model" not in pinned:
178
193
  self.cfg.model = endpoint["model"]
179
194
  if "provider" not in pinned:
@@ -455,6 +470,94 @@ class Workbench:
455
470
  )
456
471
  return result
457
472
 
473
+ def save_profile(self, name: str, provider: str, base_url: str,
474
+ api_key: str, model: str) -> ActionResult:
475
+ """Create or overwrite a stored profile from form values (F7 表单).
476
+
477
+ A *new* profile is switched to immediately — creating an endpoint
478
+ in-session means using it now. Overwriting the *current* profile
479
+ re-adopts its fields so provider/base_url edits take effect on
480
+ the next turn; other profiles are saved without switching.
481
+ ``provider == "none"`` (the form's sentinel) stores no preset and
482
+ explicitly clears one the profile previously had.
483
+ """
484
+ result = ActionResult(changed=True)
485
+ clean = (name or "").strip()
486
+ provider = (provider or "").strip()
487
+ provider = "" if provider.lower() in ("", "none", "off") else provider
488
+ if not clean:
489
+ result.say("err", "档案名不能为空")
490
+ return result
491
+ if not ((base_url or "").strip() and (api_key or "").strip()
492
+ and (model or "").strip()):
493
+ result.say("err", "base_url / API key / 模型 均不能为空")
494
+ return result
495
+ existed = clean in self.profiles.names()
496
+ had_provider = None
497
+ if existed:
498
+ try:
499
+ had_provider = self.profiles.endpoint(clean).get("provider")
500
+ except SystemExit:
501
+ had_provider = None
502
+ try:
503
+ self.profiles.upsert(clean, base_url.strip(), api_key.strip(),
504
+ model.strip(),
505
+ provider=provider or None)
506
+ except SystemExit as exc:
507
+ result.say("err", str(exc.code))
508
+ return result
509
+ if not provider and had_provider:
510
+ try:
511
+ self.profiles.set_provider(clean, None)
512
+ except ValueError:
513
+ pass
514
+ if not existed:
515
+ switch = self.set_profile(clean)
516
+ result.messages.extend(switch.messages)
517
+ return result
518
+ if clean == self.cfg.profile:
519
+ try:
520
+ self._apply_endpoint(self.profiles.endpoint(clean))
521
+ except SystemExit:
522
+ pass
523
+ dialect = self._endpoint_dialect(
524
+ {"provider": provider or None,
525
+ "base_url": base_url.strip()})
526
+ result.say("ok", f"档案 {clean} 已更新"
527
+ f"{'(' + dialect + ')' if dialect else ''},下一轮生效")
528
+ else:
529
+ result.say("ok", f"档案 {clean} 已保存(Enter 可切换)")
530
+ return result
531
+
532
+ def change_profile_provider(self, name: str, provider: str) -> ActionResult:
533
+ """Swap a stored profile's provider preset (F7 › p).
534
+
535
+ ``none``/``off``/empty clears it. When the profile is the current
536
+ one, its fields are re-adopted so the transport/dialect change
537
+ applies to the next turn.
538
+ """
539
+ result = ActionResult(changed=True)
540
+ if name not in self.profiles.names():
541
+ result.say("err", f"未知档案 {name}")
542
+ return result
543
+ try:
544
+ self.profiles.set_provider(name, provider)
545
+ except ValueError as exc:
546
+ result.say("err", str(exc))
547
+ return result
548
+ raw = (provider or "").strip()
549
+ if raw.lower() in ("", "none", "off"):
550
+ result.say("ok", f"档案 {name} 已清除 provider(手写端点)")
551
+ else:
552
+ result.say("ok", f"档案 {name} provider → {raw.lower()}")
553
+ if name == self.cfg.profile:
554
+ try:
555
+ self._apply_endpoint(self.profiles.endpoint(name))
556
+ except SystemExit:
557
+ pass
558
+ result.say("dim", "下一轮生效")
559
+ return result
560
+
458
561
  async def fetch_model_list(self, scope: str = "current") -> ActionResult:
459
562
  """Fetch ``/models`` per protocol (see ``fetch_models_for``).
460
563
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.12
3
+ Version: 0.2.1
4
4
  Summary: Command-line interface for the lithe agent kernel: chat, one-shot runs, undo, and run inspection.
5
5
  License: MIT License
6
6
 
@@ -158,7 +158,7 @@ $ lithe run "总结 README.md 的要点,存到 SUMMARY.md"
158
158
  ── done · steps 3 · tokens 2100 · cost 0.0042
159
159
  ```
160
160
 
161
- 修改已有文件时,助手优先调用 `edit_file` 或 `apply_patch` 做局部更新;只有新建文件或需要整体替换时才使用 `write_file`。工具调用界面只显示工具名、文件路径等摘要,文件写入/编辑的结果带 `+N -M 行` 的行数变化提示(lithe 0.9.10 起由内核统计)。
161
+ 修改已有文件时,助手优先调用 `edit_file` 或 `apply_patch` 做局部更新;只有新建文件或需要整体替换时才使用 `write_file`。工具调用界面只显示工具名、文件路径等摘要,文件写入/编辑的结果带 `+N -M 行` 的行数变化提示(lithe 0.1.0 起由内核统计)。
162
162
 
163
163
  `--stream` streams tokens as they generate; `-v` adds per-call
164
164
  usage/context gauges; `--max-steps` caps the tool loop;
@@ -181,7 +181,7 @@ the conversation; the right sidebar is five fixed sections — 会话(current
181
181
  工具/待办、用量:
182
182
 
183
183
  ```text
184
- lithe 0.9.0 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
184
+ lithe 0.2.1 · ▣ #12 重构计划 │ zhipu · glm-4.6 │ ~/myproj ● 运行中
185
185
  ╭──────────────────────────────────────╮╭──────────────────────────╮
186
186
  │ 把 a.txt 改成三行待办清单 ││ ◆ 会话 │
187
187
  │ ◆ edit_file · 局部修改 a.txt ││ #12 重构计划 ● │
@@ -189,19 +189,27 @@ the conversation; the right sidebar is five fixed sections — 会话(current
189
189
  │ 已完成。 ││ F3 切换 · /new 新建 │
190
190
  │ ││ ◆ 模型 │
191
191
  │ ││ zhipu · glm-4.6 │
192
+ │ ││ zai · chat · F7 端点 │
192
193
  │ ││ ◆ 会话用量 │
193
194
  │ ││ 输入 1,024 · 输出 216 │
194
195
  ╰──────────────────────────────────────╯╰──────────────────────────╯
195
196
  Tab 采纳 → /model /models /new
196
197
  lithe ❯ _
197
- ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · /help
198
+ ● 运行中 · 步骤 2/35 Enter 发送 · F2 侧栏 · F3 会话 · F4 模型 · F5 设置 · F6 推理 · F7 端点 · /help
198
199
  ```
199
200
 
200
201
  **Switch without leaving the screen**: `F3` opens the session picker
201
202
  (`Enter` switch, `n` new, `d` delete, `r` rename), `F4` the model picker
202
203
  (grouped by profile; `Enter` switch, `s` save as the profile's default,
203
- `r` fetch `/models`), and `F5` the settings picker (`Enter` toggles a
204
- capability; see below). Switching away from a running session does **not**
204
+ `r` fetch `/models`), `F5` the settings picker (`Enter` toggles a
205
+ capability; see below), and `F7` the **endpoint manager** — every saved
206
+ profile with its `provider · transport` dialect, base_url and masked
207
+ key; `Enter` switches, `n` creates a profile right in the form (provider
208
+ type cycled with Enter, base_url defaulting to each preset's official
209
+ URL — overridable for custom routers, star-echoed API key), `e` edits
210
+ one, `p` swaps its provider type. A profile created in the form is
211
+ switched to on save; edits to the current profile apply to the next
212
+ turn. Switching away from a running session does **not**
205
213
  cancel it — its badge stays lit and the pane rebuilds from the store when
206
214
  you come back. Typing `/` shows matching commands above the prompt (`Tab`
207
215
  accepts; `/model`, `/profile`, `/set` complete their arguments too),
@@ -926,7 +926,183 @@ def test_feed_text_is_renderable_verbatim_not_as_markup(tmp_path, copied):
926
926
  await pilot.press("enter")
927
927
  await pilot.pause()
928
928
  assert copied[-1] == answer
929
+ asyncio.run(scenario())
930
+
931
+
932
+ # -- F7 端点管理:表单 + 选择器 ------------------------------------------------------
933
+
934
+ def test_sidebar_shows_endpoint_dialect_and_footer_f7():
935
+ state = TuiState("glm-4.6", "/ws", 35, profile="zhipu")
936
+ state.dialect = "zai · chat"
937
+ state.temperature = 0.7
938
+ state.max_output = 8192
939
+ side = sidebar_markup(state)
940
+ assert "zai · chat · F7 端点" in side
941
+ assert "温度 0.7" in side and "输出上限 8,192" in side
942
+ assert "F7 端点" in footer_text(state)
943
+ # 无 dialect 时仍有 F7 入口提示
944
+ state.dialect = ""
945
+ assert "F7 端点管理" in sidebar_markup(state)
946
+
947
+
948
+ def test_form_modal_advances_cycles_and_submits():
949
+ changes: list = []
950
+
951
+ async def scenario():
952
+ fields = [
953
+ {"name": "profile", "label": "档案名", "kind": "text"},
954
+ {"name": "provider", "label": "Provider", "kind": "choice",
955
+ "choices": ["none", "anthropic", "zai"], "default": "none"},
956
+ {"name": "base_url", "label": "Base URL", "kind": "text"},
957
+ {"name": "api_key", "label": "API key", "kind": "password"},
958
+ {"name": "model", "label": "模型", "kind": "text"},
959
+ ]
960
+
961
+ def on_change(field, value):
962
+ changes.append((field, value))
963
+ if field == "provider":
964
+ form.set_value("base_url", "https://preset.example/v1")
965
+
966
+ got: list = []
967
+ from lithe_cli.ttui_widgets import FormModal
968
+ from textual.app import App as TextualApp
969
+
970
+ class Host(TextualApp):
971
+ pass
972
+
973
+ app = Host()
974
+ form = FormModal("测试表单", fields, hint="提示", on_change=on_change)
975
+ async with app.run_test(size=(80, 24)) as pilot:
976
+ app.push_screen(form, got.append)
977
+ await pilot.pause()
978
+ # 档案名 → Provider(Enter 前进)
979
+ await pilot.press(*"myrouter")
980
+ await pilot.press("enter")
981
+ # Provider 行 Enter 循环:none → anthropic,并预填 base_url
982
+ await pilot.press("enter")
983
+ assert changes[-1] == ("provider", "anthropic")
984
+ # base_url 已预填,Tab 跳过 → api_key → model → 末项 Enter 提交
985
+ await pilot.press("tab")
986
+ await pilot.press("enter")
987
+ await pilot.press(*"sk-demo")
988
+ await pilot.press("enter")
989
+ await pilot.press(*"glm-4.6")
990
+ await pilot.press("enter")
991
+ await pilot.pause()
992
+ assert got and got[0][0] == "submit"
993
+ values = got[0][1]
994
+ assert values["profile"] == "myrouter"
995
+ assert values["provider"] == "anthropic"
996
+ assert values["base_url"] == "https://preset.example/v1"
997
+ assert values["api_key"] == "sk-demo"
998
+ assert values["model"] == "glm-4.6"
999
+
1000
+ asyncio.run(scenario())
1001
+
1002
+
1003
+ def test_form_modal_blocks_blank_required_fields():
1004
+ from lithe_cli.ttui_widgets import FormModal
1005
+ from textual.app import App as TextualApp
1006
+ from textual.widgets import Static as TextStatic
1007
+
1008
+ class Host(TextualApp):
1009
+ pass
1010
+
1011
+ async def scenario():
1012
+ fields = [
1013
+ {"name": "profile", "label": "档案名", "kind": "text"},
1014
+ {"name": "model", "label": "模型", "kind": "text"},
1015
+ ]
1016
+ got: list = []
1017
+ app = Host()
1018
+ form = FormModal("测试表单", fields, hint="提示")
1019
+ async with app.run_test(size=(80, 24)) as pilot:
1020
+ app.push_screen(form, got.append)
1021
+ await pilot.pause()
1022
+ form.action_submit() # 空表单直接提交:提示缺项,不 dismiss
1023
+ await pilot.pause()
1024
+ assert got == []
1025
+ assert "还需填写" in str(
1026
+ form.query_one("#picker-hint", TextStatic).content)
1027
+ # 填完再提交成功(set_value 同步 _values,直接改 .value 只进 widget)
1028
+ form.set_value("profile", "p")
1029
+ form.set_value("model", "m")
1030
+ form.action_submit()
1031
+ await pilot.pause()
1032
+ assert got and got[0] == ("submit", {"profile": "p", "model": "m"})
929
1033
 
930
1034
  asyncio.run(scenario())
931
1035
 
1036
+
1037
+ def test_f7_endpoint_picker_lists_and_switches(tmp_path, monkeypatch):
1038
+ monkeypatch.setenv("LITHE_HOME", str(tmp_path / "home"))
1039
+
1040
+ async def scenario():
1041
+ app = _app(tmp_path, [{"content": "ok"}])
1042
+ async with app.run_test(size=(100, 30)) as pilot:
1043
+ app.wb.profiles.upsert("a", "https://a.example/api", "sk-a",
1044
+ "m-a")
1045
+ app.wb.profiles.upsert("b", "https://b.example/api", "sk-b",
1046
+ "m-b", provider="zai")
1047
+ app._refresh_meta()
1048
+ app.action_open_endpoint()
1049
+ await pilot.pause()
1050
+ assert isinstance(app.screen, PickerModal)
1051
+ assert app.screen.title == "端点档案"
1052
+ labels = [label for _payload, label in app.screen.items]
1053
+ assert any("zai · chat" in lab and "m-b" in lab for lab in labels)
1054
+ # 第二行(b)回车 → 切换档案,整套端点真相生效
1055
+ await pilot.press("down")
1056
+ await pilot.press("enter")
1057
+ await pilot.pause()
1058
+ assert app.cfg.profile == "b"
1059
+ assert app.cfg.base_url == "https://b.example/api"
1060
+ assert app.cfg.model == "m-b"
1061
+ assert app.state.dialect == "zai · chat"
1062
+
1063
+ asyncio.run(scenario())
1064
+
1065
+
1066
+ def test_f7_form_creates_profile_end_to_end(tmp_path, monkeypatch):
1067
+ monkeypatch.setenv("LITHE_HOME", str(tmp_path / "home"))
1068
+
1069
+ async def scenario():
1070
+ app = _app(tmp_path, [{"content": "ok"}])
1071
+ async with app.run_test(size=(100, 30)) as pilot:
1072
+ app.action_open_endpoint()
1073
+ await pilot.pause()
1074
+ # 空档案列表 → n 打开表单
1075
+ await pilot.press("n")
1076
+ await pilot.pause(0.2)
1077
+ from lithe_cli.ttui_widgets import FormModal
1078
+
1079
+ assert isinstance(app.screen, FormModal)
1080
+ form = app.screen
1081
+ await pilot.press(*"myrouter")
1082
+ await pilot.press("enter") # → Provider
1083
+ # 循环到 openrouter(选择列表按字母序,逐次 Enter 换档)
1084
+ for _ in range(14):
1085
+ if form.values()["provider"] == "openrouter":
1086
+ break
1087
+ await pilot.press("enter")
1088
+ await pilot.pause()
1089
+ assert form.values()["provider"] == "openrouter"
1090
+ await pilot.press("tab") # base_url(Tab 全选了预填的官方 URL)
1091
+ base = form.values()["base_url"]
1092
+ assert base == "https://openrouter.ai/api/v1"
1093
+ # 直接键入自己的路由 URL(Tab 进入时全选,输入即整体替换)
1094
+ await pilot.press(*"https://my-router/api/v1")
1095
+ await pilot.press("enter") # → api_key
1096
+ await pilot.press(*"sk-or")
1097
+ await pilot.press("enter") # → model
1098
+ await pilot.press(*"vendor/claude-sonnet-4")
1099
+ await pilot.press("enter") # 末项 → 保存
1100
+ await pilot.pause()
1101
+ assert app.cfg.profile == "myrouter"
1102
+ assert app.cfg.provider == "openrouter"
1103
+ assert app.cfg.base_url == "https://my-router/api/v1"
1104
+ ep = app.wb.profiles.endpoint("myrouter")
1105
+ assert ep["provider"] == "openrouter"
1106
+ assert ep["model"] == "vendor/claude-sonnet-4"
1107
+
932
1108
  asyncio.run(scenario())
@@ -518,11 +518,89 @@ def test_reasoning_save_persists_to_profile(tmp_path, monkeypatch):
518
518
  wb.cfg.profile = "zai"
519
519
  wb.dispatch("/reasoning high --save")
520
520
  assert wb.profiles.endpoint("zai")["reasoning_effort"] == "high"
521
+
521
522
  # off + --save 清除档案字段
522
523
  wb.dispatch("/reasoning off --save")
523
524
  assert "reasoning_effort" not in wb.profiles.endpoint("zai")
524
525
 
525
526
 
527
+ # --- F7 端点表单:save_profile / change_profile_provider --------------------------
528
+
529
+ def _wb_home(tmp_path, monkeypatch, responses=None) -> Workbench:
530
+ monkeypatch.setenv("LITHE_HOME", str(tmp_path / "home"))
531
+ return _wb(tmp_path, responses or [{"content": "ok"}])
532
+
533
+
534
+ def test_save_profile_new_switches_immediately(tmp_path, monkeypatch):
535
+ wb = _wb_home(tmp_path, monkeypatch)
536
+ r = wb.save_profile("myrouter", "openrouter",
537
+ "https://my-router/api/v1", "sk-r",
538
+ "vendor/claude-sonnet-4")
539
+ assert r.messages[0][0] == "ok"
540
+ assert wb.cfg.profile == "myrouter"
541
+ assert wb.cfg.provider == "openrouter"
542
+ assert wb.cfg.base_url == "https://my-router/api/v1"
543
+ ep = wb.profiles.endpoint("myrouter")
544
+ assert ep["provider"] == "openrouter"
545
+ assert ep["model"] == "vendor/claude-sonnet-4"
546
+
547
+
548
+ def test_save_profile_edit_current_reapplies(tmp_path, monkeypatch):
549
+ wb = _wb_home(tmp_path, monkeypatch)
550
+ wb.profiles.upsert("cur", "https://old.example/api", "sk", "m")
551
+ wb.set_profile("cur")
552
+ r = wb.save_profile("cur", "anthropic",
553
+ "https://api.anthropic.com/v1", "sk-ant",
554
+ "claude-sonnet-4")
555
+ assert wb.cfg.provider == "anthropic"
556
+ assert wb.cfg.base_url == "https://api.anthropic.com/v1"
557
+ assert wb.cfg.model == "claude-sonnet-4"
558
+ assert any("下一轮生效" in t for _, t in r.messages)
559
+
560
+
561
+ def test_save_profile_none_clears_existing_provider(tmp_path, monkeypatch):
562
+ wb = _wb_home(tmp_path, monkeypatch)
563
+ wb.profiles.upsert("a", "https://a.example/api", "sk", "m", provider="zai")
564
+ wb.save_profile("a", "none", "https://a.example/api", "sk", "m2")
565
+ assert "provider" not in wb.profiles.endpoint("a")
566
+ assert wb.cfg.provider is None
567
+
568
+
569
+ def test_save_profile_validation_and_bad_name(tmp_path, monkeypatch):
570
+ wb = _wb_home(tmp_path, monkeypatch)
571
+ assert wb.save_profile("", "none", "https://x", "k",
572
+ "m").messages[0][0] == "err"
573
+ assert wb.save_profile("b", "none", "", "k", "m").messages[0][0] == "err"
574
+ assert wb.save_profile("bad name!", "none", "https://x", "k",
575
+ "m").messages[0][0] == "err"
576
+
577
+
578
+ def test_change_profile_provider_current_and_clear(tmp_path, monkeypatch):
579
+ wb = _wb_home(tmp_path, monkeypatch)
580
+ wb.profiles.upsert("a", "", "sk", "glm-4.6", provider="zai")
581
+ wb.set_profile("a")
582
+ assert wb.cfg.provider == "zai"
583
+ r = wb.change_profile_provider("a", "Anthropic")
584
+ assert wb.profiles.endpoint("a")["provider"] == "anthropic"
585
+ assert wb.cfg.provider == "anthropic"
586
+ # preset-only 档案切换 provider 后,官方 base_url 跟着换
587
+ assert wb.cfg.base_url == "https://api.anthropic.com/v1"
588
+ assert any("下一轮生效" in t for _, t in r.messages)
589
+ wb.change_profile_provider("a", "off")
590
+ assert "provider" not in wb.profiles.endpoint("a")
591
+ assert wb.cfg.provider is None
592
+ assert wb.change_profile_provider("ghost", "zai").messages[0][0] == "err"
593
+ assert wb.change_profile_provider("a", "nope").messages[0][0] == "err"
594
+
595
+
596
+ def test_switch_to_preset_only_profile_fills_base_url(tmp_path, monkeypatch):
597
+ """档案只写 provider 不写 base_url:会话内切换不得把端点清空。"""
598
+ wb = _wb_home(tmp_path, monkeypatch)
599
+ wb.profiles.upsert("preset-only", "", "sk", "glm-4.6", provider="zai")
600
+ wb.set_profile("preset-only")
601
+ assert wb.cfg.base_url == "https://open.bigmodel.cn/api/paas/v4"
602
+
603
+
526
604
  def test_reasoning_effort_reaches_llm_config(tmp_path):
527
605
  from lithe_cli.agent import build_llm
528
606
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes