pi-model-manager 0.4.9 → 0.4.10

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.
@@ -0,0 +1,439 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import * as native from "@earendil-works/pi-tui";
3
+ import type { Component, Focusable, TUI } from "@earendil-works/pi-tui";
4
+ import { formatUnknownError } from "../common.ts";
5
+ import { ui, type Choice, type WorkbenchRow, type WorkbenchView } from "./workbench-types.ts";
6
+
7
+ interface ListState { selected: string; query: string; offset: number }
8
+ interface Picker {
9
+ title: string;
10
+ options: Choice[];
11
+ selected: string;
12
+ query: string;
13
+ searching: boolean;
14
+ searchable: boolean;
15
+ message?: string;
16
+ rank?: (ids: string[], query: string) => string[];
17
+ messageOffset: number;
18
+ messageHeight: number;
19
+ cache?: { query: string; options: Choice[] };
20
+ resolve: (id: string | undefined) => void;
21
+ }
22
+ interface Editing {
23
+ row: WorkbenchRow;
24
+ component: native.Input | native.Editor;
25
+ multiline: boolean;
26
+ pair?: { name: native.Input; value: native.Input };
27
+ error?: string;
28
+ }
29
+
30
+ function fit(text: string, width: number): string {
31
+ const line = native.truncateToWidth(text, Math.max(0, width), "…");
32
+ return line + " ".repeat(Math.max(0, width - native.visibleWidth(line)));
33
+ }
34
+
35
+ function plain(text: string): string {
36
+ return text.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
37
+ }
38
+
39
+ function matches(data: string, key: string): boolean { return native.matchesKey(data, key as native.KeyId); }
40
+
41
+ function rowDescription(row: WorkbenchRow | undefined): string | undefined {
42
+ return [row?.description, row?.options?.find((option) => option.id === row.selected)?.description].filter(Boolean).join("\n") || undefined;
43
+ }
44
+
45
+ export class ModelManagerWindow implements Component, Focusable {
46
+ focused = false;
47
+ private lists = new Map<string, ListState>();
48
+ private searching = false;
49
+ private searchInput = new native.Input();
50
+ private editing?: Editing;
51
+ private picker?: Picker;
52
+ private pickerInput = new native.Input();
53
+ private busy?: { label: string; abort?: () => void };
54
+ private running = false;
55
+ private closed = false;
56
+ private bodyHeight = 12;
57
+ private pageSize = 1;
58
+ private pickerPageSize = 1;
59
+ private tooSmall = false;
60
+ private notice?: { text: string; error: boolean };
61
+
62
+ private tui: TUI;
63
+ private theme: Theme;
64
+ private getView: () => WorkbenchView;
65
+ private done: () => void;
66
+
67
+ constructor(tui: TUI, theme: Theme, getView: () => WorkbenchView, done: () => void) {
68
+ this.tui = tui; this.theme = theme; this.getView = getView; this.done = done;
69
+ }
70
+
71
+ get disposed(): boolean { return this.closed; }
72
+ invalidate(): void { this.editing?.component.invalidate(); }
73
+ refresh(): void { if (!this.closed) this.tui.requestRender(); }
74
+ notify(text: string, error = false): void {
75
+ this.notice = { text: this.notice ? `${this.notice.text}\n${text}` : text, error: error || !!this.notice?.error };
76
+ this.refresh();
77
+ }
78
+ focusContent(id?: string): void {
79
+ this.searching = false;
80
+ if (id) this.state(this.getView().page.id).selected = id;
81
+ this.refresh();
82
+ }
83
+ selectRow(pageId: string, id: string): void { this.state(pageId).selected = id; }
84
+ selectedRow(): string | undefined { return this.currentRows(this.getView()).selected?.id; }
85
+ preservePageState(previousId: string): void {
86
+ const nextId = this.getView().page.id;
87
+ const state = this.lists.get(previousId);
88
+ if (state && nextId !== previousId) { this.lists.set(nextId, state); this.lists.delete(previousId); }
89
+ }
90
+
91
+ close(): void { if (this.closed) return; this.dispose(); this.done(); }
92
+ dispose(): void {
93
+ this.closed = true;
94
+ this.busy?.abort?.();
95
+ this.picker?.resolve(undefined);
96
+ this.picker = undefined;
97
+ this.editing = undefined;
98
+ this.lists.clear();
99
+ }
100
+
101
+ async choose(title: string, options: Choice[], selected?: string, settings: { message?: string; searchable?: boolean; rank?: Picker["rank"] } = {}): Promise<string | undefined> {
102
+ if (this.closed) return undefined;
103
+ return new Promise((resolve) => {
104
+ this.pickerInput.setValue("");
105
+ this.picker = { title, options, selected: selected ?? options[0]?.id ?? "", query: "", searching: false, searchable: settings.searchable ?? false, messageOffset: 0, messageHeight: 1, ...settings, resolve };
106
+ this.refresh();
107
+ });
108
+ }
109
+
110
+ async confirm(title: string, message: string): Promise<boolean> {
111
+ return await this.choose(title, [
112
+ { id: "cancel", label: ui("取消", "Cancel") }, { id: "confirm", label: ui("确认", "Confirm") },
113
+ ], "cancel", { message }) === "confirm";
114
+ }
115
+
116
+ async wait<T>(label: string, operation: () => Promise<T>, abort?: () => void): Promise<T> {
117
+ this.busy = { label, abort }; this.refresh();
118
+ try { return await operation(); }
119
+ finally { this.busy = undefined; this.refresh(); }
120
+ }
121
+
122
+ private state(id: string): ListState {
123
+ let state = this.lists.get(id);
124
+ if (!state) { state = { selected: "", query: "", offset: 0 }; this.lists.set(id, state); }
125
+ return state;
126
+ }
127
+
128
+ private filtered(rows: WorkbenchRow[], query: string): WorkbenchRow[] {
129
+ const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
130
+ return terms.length ? rows.filter((row) => terms.every((term) => (row.searchText ?? `${row.label} ${row.value ?? ""}`).toLowerCase().includes(term))) : rows;
131
+ }
132
+
133
+ private currentRows(view: WorkbenchView) {
134
+ const state = this.state(view.page.id);
135
+ const rows = this.filtered(view.page.rows, state.query);
136
+ if (!rows.some((row) => row.id === state.selected)) state.selected = rows[0]?.id ?? "";
137
+ return { state, rows, selected: rows.find((row) => row.id === state.selected) };
138
+ }
139
+
140
+ private run(action: () => void | Promise<void>): void {
141
+ if (this.running || this.closed) return;
142
+ this.running = true;
143
+ this.notice = undefined;
144
+ Promise.resolve().then(action).catch((error) => this.notify(formatUnknownError(error), true)).finally(() => { this.running = false; this.refresh(); });
145
+ }
146
+
147
+ private move(data: string, index: number, count: number): number | undefined {
148
+ let next: number;
149
+ const pageSize = this.picker ? this.pickerPageSize : this.pageSize;
150
+ if (matches(data, "up")) next = index - 1;
151
+ else if (matches(data, "down")) next = index + 1;
152
+ else if (matches(data, "pageUp")) next = index - pageSize;
153
+ else if (matches(data, "pageDown")) next = index + pageSize;
154
+ else if (matches(data, "home")) next = 0;
155
+ else if (matches(data, "end")) next = count - 1;
156
+ else return undefined;
157
+ return Math.max(0, Math.min(count - 1, next));
158
+ }
159
+
160
+ editRow(row: WorkbenchRow | undefined): void {
161
+ if (!row) return;
162
+ if (row.pair) {
163
+ const name = new native.Input(); name.setValue(row.pair.name);
164
+ const value = new native.Input(); value.setValue(row.pair.value);
165
+ this.editing = { row, component: row.pair.initial === "name" ? name : value, multiline: false, pair: { name, value } };
166
+ } else if (row.edit) {
167
+ const multiline = !!row.edit.multiline;
168
+ const component = multiline ? new native.Editor(this.tui, {
169
+ borderColor: (s) => this.theme.fg("borderMuted", s),
170
+ selectList: { selectedPrefix: (s) => this.theme.fg("accent", s), selectedText: (s) => this.theme.fg("accent", s), description: (s) => this.theme.fg("muted", s), scrollInfo: (s) => this.theme.fg("dim", s), noMatch: (s) => this.theme.fg("warning", s) },
171
+ }, { paddingX: 0 }) : new native.Input();
172
+ if (component instanceof native.Editor) { component.setText(row.edit.value); component.disableSubmit = true; }
173
+ else component.setValue(row.edit.value);
174
+ this.editing = { row, component, multiline };
175
+ } else if (row.options && row.select) this.run(async () => {
176
+ const value = await this.choose(row.label, row.options!, row.selected, { searchable: row.options!.length > 6 });
177
+ if (value !== undefined) await row.select!(value);
178
+ });
179
+ else if (row.activate) this.run(row.activate);
180
+ }
181
+
182
+ private finishEdit(): boolean {
183
+ if (!this.editing) return true;
184
+ const { component, row, pair } = this.editing;
185
+ try {
186
+ if (pair) row.pair!.apply(pair.name.getValue(), pair.value.getValue());
187
+ else row.edit!.apply(component instanceof native.Editor ? component.getExpandedText() : component.getValue());
188
+ this.editing = undefined;
189
+ return true;
190
+ } catch (error) { this.editing.error = formatUnknownError(error); return false; }
191
+ }
192
+
193
+ handleInput(data: string): void {
194
+ if (this.closed) return;
195
+ try { this.handle(data); }
196
+ catch (error) { this.notify(formatUnknownError(error), true); }
197
+ this.refresh();
198
+ }
199
+
200
+ private handle(data: string): void {
201
+ if (matches(data, "ctrl+c")) data = "\x1b";
202
+ if (this.tooSmall && !matches(data, "escape")) return;
203
+ if (this.picker) { this.handlePicker(data); return; }
204
+ if (this.busy) { if (matches(data, "escape")) this.busy.abort?.(); return; }
205
+ if (this.running) return;
206
+ const view = this.getView();
207
+ if (this.editing) {
208
+ if (matches(data, "escape")) { this.editing = undefined; return; }
209
+ if (matches(data, "ctrl+s")) { if (this.finishEdit() && view.page.save) this.run(view.page.save); return; }
210
+ const pair = this.editing.pair;
211
+ if (pair && (matches(data, "tab") || matches(data, "shift+tab") || matches(data, "enter") && this.editing.component === pair.name)) {
212
+ this.editing.component = this.editing.component === pair.name ? pair.value : pair.name;
213
+ return;
214
+ }
215
+ if (matches(data, this.editing.multiline ? "ctrl+enter" : "enter") || (!this.editing.multiline && matches(data, "tab"))) { this.finishEdit(); return; }
216
+ if (this.editing.multiline && matches(data, "enter")) this.editing.component.handleInput("\x1b[13;2u");
217
+ else this.editing.component.handleInput(data);
218
+ return;
219
+ }
220
+ const list = this.currentRows(view);
221
+ if (this.searching) {
222
+ if (matches(data, "tab") || matches(data, "shift+tab")) { this.searching = false; return; }
223
+ if (matches(data, "escape")) { this.searching = false; list.state.query = ""; return; }
224
+ if (matches(data, "enter")) { this.searching = false; this.editRow(list.selected); return; }
225
+ const next = matches(data, "up") || matches(data, "down") || matches(data, "pageUp") || matches(data, "pageDown") ? this.move(data, list.rows.findIndex((r) => r.id === list.state.selected), list.rows.length) : undefined;
226
+ if (next !== undefined) list.state.selected = list.rows[next]?.id ?? "";
227
+ else { this.searchInput.handleInput(data); list.state.query = this.searchInput.getValue(); }
228
+ return;
229
+ }
230
+ if (matches(data, "ctrl+s")) { if (view.page.save) this.run(view.page.save); return; }
231
+ if (matches(data, "escape")) {
232
+ if (list.state.query) list.state.query = "";
233
+ else this.run(view.page.back);
234
+ return;
235
+ }
236
+ if (matches(data, "?") || matches(data, "shift+/")) {
237
+ const message = [this.notice?.text, rowDescription(list.selected), view.page.summary, view.page.details, this.hints(view).map(([key, label]) => `${key} ${label}`).join(" · ")].filter(Boolean).join("\n");
238
+ this.run(async () => { await this.choose(ui("详细信息", "Details"), [{ id: "back", label: ui("返回", "Back") }], "back", { message }); });
239
+ return;
240
+ }
241
+ const action = [...(list.selected?.actions ?? []), ...view.page.actions].find((action) => matches(data, action.key) || matches(data, `shift+${action.key}`));
242
+ if (action) {
243
+ if (!action.requiresSelection || list.selected) this.run(action.run);
244
+ return;
245
+ }
246
+ if ((matches(data, "/") || matches(data, "tab") && !!list.state.query) && view.page.searchable) {
247
+ this.searching = true; this.searchInput.setValue(list.state.query); return;
248
+ }
249
+ const next = this.move(data, list.rows.findIndex((r) => r.id === list.state.selected), list.rows.length);
250
+ if (next !== undefined) {
251
+ list.state.selected = list.rows[next]?.id ?? "";
252
+ this.notice = undefined;
253
+ } else if (matches(data, "enter")) this.editRow(list.selected);
254
+ else if (matches(data, "left") || matches(data, "right")) {
255
+ const adjust = list.selected?.adjust;
256
+ if (adjust) this.run(() => adjust(matches(data, "left") ? -1 : 1));
257
+ }
258
+ }
259
+
260
+ private pickerOptions(picker: Picker): Choice[] {
261
+ if (picker.cache?.query === picker.query) return picker.cache.options;
262
+ let options: Choice[];
263
+ if (picker.rank) {
264
+ const lookup = new Map(picker.options.map((option) => [option.id, option]));
265
+ options = picker.rank([...lookup.keys()], picker.query).map((id) => lookup.get(id)!);
266
+ } else options = picker.options.filter((option) => `${option.label} ${option.description ?? ""}`.toLowerCase().includes(picker.query.toLowerCase()));
267
+ picker.cache = { query: picker.query, options };
268
+ return options;
269
+ }
270
+
271
+ private handlePicker(data: string): void {
272
+ const picker = this.picker!;
273
+ const finish = (value?: string) => { this.picker = undefined; picker.resolve(value); };
274
+ const options = this.pickerOptions(picker);
275
+ if (!options.some((option) => option.id === picker.selected)) picker.selected = options[0]?.id ?? "";
276
+ if (matches(data, "escape")) {
277
+ if (picker.searching || picker.query) { picker.searching = false; picker.query = ""; }
278
+ else finish();
279
+ return;
280
+ }
281
+ if (picker.message && (matches(data, "pageUp") || matches(data, "pageDown"))) {
282
+ picker.messageOffset = Math.max(0, picker.messageOffset + (matches(data, "pageUp") ? -1 : 1) * picker.messageHeight);
283
+ return;
284
+ }
285
+ if (matches(data, "enter")) { if (options.some((option) => option.id === picker.selected)) finish(picker.selected); return; }
286
+ if (picker.searchable && matches(data, "tab")) { picker.searching = !picker.searching; this.pickerInput.setValue(picker.query); return; }
287
+ if (picker.searchable && !picker.searching && matches(data, "/")) { picker.searching = true; this.pickerInput.setValue(picker.query); return; }
288
+ const cursorKey = matches(data, "home") || matches(data, "end");
289
+ const next = picker.searching && cursorKey ? undefined : this.move(data, options.findIndex((option) => option.id === picker.selected), options.length);
290
+ if (next !== undefined) picker.selected = options[next]?.id ?? "";
291
+ else if (picker.searching) { this.pickerInput.handleInput(data); picker.query = this.pickerInput.getValue(); }
292
+ }
293
+
294
+ private listLines(view: WorkbenchView, width: number, height: number): string[] {
295
+ const { rows, state } = this.currentRows(view);
296
+ const lines: string[] = [];
297
+ if ((state.query || this.searching) && height > 1) {
298
+ this.searchInput.focused = this.focused && this.searching;
299
+ lines.push(this.searching ? this.searchInput.render(width)[0]! : this.theme.fg("muted", `/ ${plain(state.query)}`));
300
+ }
301
+ if (view.page.tableHeader && height - lines.length > 2) lines.push(this.theme.bold(this.theme.fg("text", view.page.tableHeader(width))));
302
+ const items: ({ row: WorkbenchRow; id: string } | { group: string; id?: undefined })[] = [];
303
+ let group: string | undefined;
304
+ for (const row of rows) {
305
+ if (row.group && row.group !== group) {
306
+ group = row.group;
307
+ if (height >= 12) items.push({ group });
308
+ }
309
+ items.push({ row, id: row.id });
310
+ }
311
+ let capacity = Math.max(1, height - lines.length);
312
+ const scrolling = items.length > capacity;
313
+ if (scrolling && capacity > 2) capacity--;
314
+ const selectedLine = Math.max(0, items.findIndex((item) => item.id === state.selected));
315
+ state.offset = Math.max(0, Math.min(state.offset, Math.max(0, items.length - capacity)));
316
+ if (selectedLine < state.offset) state.offset = selectedLine;
317
+ if (selectedLine >= state.offset + capacity) state.offset = selectedLine - capacity + 1;
318
+ const visible = items.slice(state.offset, state.offset + capacity);
319
+ const labelWidth = Math.min(26, Math.max(8, Math.floor((width - 3) * 0.38)));
320
+ for (const item of visible) {
321
+ if ("group" in item) { lines.push(this.theme.bold(this.theme.fg("accent", ` ${plain(item.group)}`))); continue; }
322
+ const row = item.row;
323
+ const selected = row.id === state.selected;
324
+ let content: string;
325
+ if (this.editing && !this.editing.multiline && this.editing.row.id === row.id) {
326
+ const pair = this.editing.pair;
327
+ if (pair) {
328
+ pair.name.focused = this.focused && this.editing.component === pair.name;
329
+ pair.value.focused = this.focused && this.editing.component === pair.value;
330
+ content = `${fit(pair.name.render(labelWidth)[0] ?? "", labelWidth)} ${pair.value.render(Math.max(1, width - labelWidth - 3))[0] ?? ""}`;
331
+ } else content = `${this.theme.fg("text", fit(plain(row.label), labelWidth))} ${this.editingLines(Math.max(1, width - labelWidth - 3), 1)[0] ?? ""}`;
332
+ } else if (row.format) content = this.theme.fg("text", row.format(Math.max(1, width - 2), this.theme));
333
+ else if (row.value !== undefined && view.page.save) {
334
+ content = `${this.theme.fg("text", fit(plain(row.label), labelWidth))} ${this.theme.fg("text", `${row.adjust ? "‹ " : ""}${plain(row.value)}${row.adjust ? " ›" : ""}`)}`;
335
+ } else if (row.value !== undefined) {
336
+ const valueWidth = Math.min(native.visibleWidth(plain(row.value)), Math.floor((width - 4) / 2));
337
+ content = this.theme.fg("text", fit(plain(row.label), width - valueWidth - 4)) + " " + this.theme.fg("muted", fit(plain(row.value), valueWidth));
338
+ } else content = this.theme.fg("text", plain(row.label));
339
+ let text = fit((selected ? this.theme.fg("accent", "› ") : " ") + content, width);
340
+ if (selected) text = this.theme.bg("selectedBg", this.theme.bold(text));
341
+ lines.push(text);
342
+ }
343
+ this.pageSize = Math.max(1, visible.filter((item) => item.id).length);
344
+ if (!rows.length) lines.push(this.theme.fg("muted", state.query ? ui("没有匹配项", "No matches") : view.page.empty ?? ui("暂无条目", "No entries")));
345
+ if (scrolling && height - lines.length > 0) lines.push(this.theme.fg("dim", `${rows.findIndex((row) => row.id === state.selected) + 1}/${rows.length} PgUp/PgDn`));
346
+ return lines.slice(0, height);
347
+ }
348
+
349
+ private pickerLines(width: number, height: number): string[] {
350
+ const picker = this.picker!;
351
+ const options = this.pickerOptions(picker);
352
+ if (!options.some((option) => option.id === picker.selected)) picker.selected = options[0]?.id ?? "";
353
+ const selected = Math.max(0, options.findIndex((option) => option.id === picker.selected));
354
+ const lines: string[] = [];
355
+ const messageText = picker.message && native.visibleWidth(plain(picker.title)) > width - 1 ? `${picker.title}\n${picker.message}` : picker.message;
356
+ const message = messageText?.split("\n").flatMap((line) => native.wrapTextWithAnsi(plain(line), width)) ?? [];
357
+ if (message.length && height > 2) {
358
+ picker.messageHeight = Math.max(1, height - Math.min(options.length, 3) - 1);
359
+ picker.messageOffset = Math.min(picker.messageOffset, Math.max(0, message.length - picker.messageHeight));
360
+ lines.push(...message.slice(picker.messageOffset, picker.messageOffset + picker.messageHeight));
361
+ if (message.length > picker.messageHeight) lines.push(this.theme.fg("dim", `${picker.messageOffset + 1}–${Math.min(message.length, picker.messageOffset + picker.messageHeight)}/${message.length} PgUp/PgDn`));
362
+ }
363
+ if (picker.searchable && height - lines.length > 1) {
364
+ this.pickerInput.focused = this.focused && picker.searching;
365
+ lines.push(picker.searching ? this.pickerInput.render(width)[0]! : this.theme.fg("muted", `/ ${plain(picker.query) || ui("搜索", "Search")}`));
366
+ }
367
+ const description = options[selected]?.description;
368
+ const descriptionLines = description && !message.length && height - lines.length > 5 ? native.wrapTextWithAnsi(plain(description), width).slice(0, 2) : [];
369
+ const counter = options.length > height - lines.length - descriptionLines.length && height - lines.length > 2;
370
+ const capacity = Math.max(1, height - lines.length - descriptionLines.length - (counter ? 1 : 0));
371
+ this.pickerPageSize = capacity;
372
+ const start = Math.max(0, Math.min(selected - capacity + 1, options.length - capacity));
373
+ lines.push(...options.slice(start, start + capacity).map((option) => option.id === picker.selected
374
+ ? this.theme.bg("selectedBg", this.theme.fg("accent", fit(`› ${plain(option.label)}`, width))) : ` ${plain(option.label)}`));
375
+ if (!options.length) lines.push(ui("没有匹配项", "No matches"));
376
+ if (counter) lines.push(this.theme.fg("dim", `${selected + 1}/${options.length} PgUp/PgDn`));
377
+ lines.push(...descriptionLines.map((line) => this.theme.fg("muted", line)));
378
+ return lines;
379
+ }
380
+
381
+ private editingLines(width: number, height: number): string[] {
382
+ const editing = this.editing!;
383
+ editing.component.focused = this.focused;
384
+ let lines = editing.component.render(width);
385
+ if (editing.row.edit?.secret) {
386
+ // [喵喵喵]: 保留原生 Input 的 ANSI/IME 光标控制,只遮罩文本,不另造一套编辑行为。
387
+ lines = lines.map((line) => line.split(/(\x1b(?:\]|_)[^\x07]*?(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~])/).map((part) => part.startsWith("\x1b") ? part : part.replace(/[^\s]+/gu, (text) => "•".repeat(native.visibleWidth(text)))).join(""));
388
+ }
389
+ const available = Math.max(1, height);
390
+ if (lines.length > available) {
391
+ const cursor = lines.findIndex((line) => line.includes(native.CURSOR_MARKER));
392
+ const start = Math.max(0, Math.min(cursor - Math.floor(available / 2), lines.length - available));
393
+ lines = lines.slice(start, start + available);
394
+ }
395
+ return [...lines];
396
+ }
397
+
398
+ private hints(view: WorkbenchView): [string, string][] {
399
+ if (this.editing) return [[this.editing.multiline ? "Ctrl+Enter" : "Enter", ui("完成", "Apply")], ...(this.editing.pair ? [["Tab", ui("名称/值", "Name/value")] as [string, string]] : []), ...(view.page.save ? [["Ctrl+S", ui("保存", "Save")] as [string, string]] : []), ["Esc", ui("取消字段", "Cancel field")]];
400
+ if (this.picker) return [["↑↓", ui("选择", "Select")], ["Enter", ui("确认", "Confirm")], ...(this.picker.message ? [["PgUp/PgDn", ui("阅读", "Read")] as [string, string]] : this.picker.searchable ? [["/", ui("搜索", "Search")] as [string, string], ["Tab", ui("列表/输入", "List/input")] as [string, string]] : []), ["Esc", ui("返回", "Back")]];
401
+ if (this.busy) return this.busy.abort ? [["Esc", ui("取消", "Cancel")]] : [];
402
+ if (this.searching) return [["↑↓", ui("选择", "Select")], ["Enter", ui("进入", "Open")], ["Tab", ui("回列表", "List")], ["Esc", ui("清空搜索", "Clear search")]];
403
+ const selected = this.currentRows(view).selected;
404
+ return [["↑↓", ui("选择", "Select")], ["Enter", view.page.enterLabel ?? ui("编辑", "Edit")], ...(selected?.adjust ? [["←→", ui("切换", "Adjust")] as [string, string]] : []), ...(view.page.save ? [["Ctrl+S", ui("保存", "Save")] as [string, string]] : []), ...[...(selected?.actions ?? []), ...view.page.actions].map((action): [string, string] => [action.key.toUpperCase(), action.label]), ...(view.page.searchable ? [["/", ui("搜索", "Search")] as [string, string]] : []), ["Esc", ui("返回", "Back")], ["?", ui("详情", "Details")]];
405
+ }
406
+
407
+ render(width: number): string[] {
408
+ const view = this.getView();
409
+ const height = Math.max(1, Math.min(32, this.tui.terminal.rows - 2));
410
+ this.tooSmall = width < 24 || height < 8;
411
+ if (this.tooSmall) return [native.truncateToWidth(ui("请放大终端 · Esc 返回", "Enlarge terminal · Esc back"), width)];
412
+ const inner = width - 4;
413
+ const title = plain(this.picker?.title ?? `${ui("模型管理", "Model manager")} / ${view.page.title}${this.editing?.multiline ? ` / ${this.editing.row.label}` : ""}`);
414
+ const dirty = !this.picker && view.page.dirty ? this.theme.fg("warning", ui(" ● 未保存", " ● Unsaved")) : "";
415
+ const heading = native.truncateToWidth(` ${title}`, Math.max(1, width - 3 - native.visibleWidth(dirty))) + dirty + " ";
416
+ const border = (text: string) => this.theme.fg("borderMuted", text);
417
+ const lines = [border("╭") + this.theme.bold(this.theme.fg("accent", heading)) + border("─".repeat(Math.max(0, width - 2 - native.visibleWidth(heading)))) + border("╮")];
418
+ const frame = (line: string) => border("│ ") + fit(line, inner) + border(" │");
419
+ const hints = this.hints(view);
420
+ let footer = native.wrapTextWithAnsi(hints.map(([key, label]) => `${this.theme.bold(this.theme.fg("accent", key))} ${this.theme.fg("text", label)}`).join(" "), inner);
421
+ if (footer.length > Math.max(2, Math.floor(height / 3))) footer = native.wrapTextWithAnsi(this.theme.bold(this.theme.fg("accent", hints.map(([key]) => key).join(" "))), inner);
422
+ const selected = this.currentRows(view).selected;
423
+ const description = this.editing?.error ?? this.notice?.text ?? rowDescription(selected) ?? view.page.summary;
424
+ const detailLimit = height >= 16 ? 2 : this.notice || this.editing?.error ? 1 : 0;
425
+ const detail = !this.picker && !this.busy && description ? description.split("\n").flatMap((line) => native.wrapTextWithAnsi(plain(line), inner)).slice(0, detailLimit) : [];
426
+ this.bodyHeight = Math.max(1, height - 3 - footer.length - detail.length);
427
+ let body: string[];
428
+ if (this.picker) body = this.pickerLines(inner, this.bodyHeight);
429
+ else if (this.busy) body = [this.theme.fg("accent", this.busy.label)];
430
+ else if (this.editing?.multiline) body = this.editingLines(inner, this.bodyHeight);
431
+ else body = this.listLines(view, inner, this.bodyHeight);
432
+ for (const line of body.slice(0, this.bodyHeight)) lines.push(frame(line));
433
+ lines.push(border(`├${"─".repeat(width - 2)}┤`));
434
+ for (const line of detail) lines.push(frame(this.theme.fg(this.editing?.error || this.notice?.error ? "error" : this.notice ? "success" : "text", line)));
435
+ for (const line of footer) lines.push(frame(line));
436
+ lines.push(border(`╰${"─".repeat(width - 2)}╯`));
437
+ return lines;
438
+ }
439
+ }