pi-model-manager 0.4.8 → 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.
@@ -1,407 +0,0 @@
1
- // tui/header-profiles-panel.ts
2
- //
3
- // 管理可复用的客户端请求头。接入编辑器只选择已存在的请求头,
4
- // 不在模型内部新增一次性 JSON,避免配置分散。
5
-
6
- import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
7
- import { formatUnknownError, parseStringRecordJson } from "../common.ts";
8
- import { t } from "../i18n.ts";
9
- import { deleteRequestHeaderProfileConfiguration, saveRequestHeaderProfileConfiguration } from "../header-profile-mutations.ts";
10
- import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "../presets/builtin-client-headers.ts";
11
- import {
12
- countModelsUsingRequestHeaderProfile,
13
- createRequestHeaderProfileDraft,
14
- createRequestHeaderProfileDraftFromStored,
15
- validateRequestHeaderProfileDraft,
16
- } from "../state-document.ts";
17
- import { readState } from "../state-store.ts";
18
- import type { RequestHeaderProfileDraft, StateDocument, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
19
- import { padLabel, showPersistentFormMenu, showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
20
- import { fitColumn, formatDetailField, formatDetailTitle } from "./ui-helpers.ts";
21
-
22
- interface ProfileRow {
23
- profileId: string;
24
- label: string;
25
- searchText: string;
26
- // [喵喵喵]: 引用计数要遍历全部 Provider,每帧重算浪费;构造行时算一次即可。
27
- usedCount: number;
28
- }
29
-
30
- interface FieldRow {
31
- id: string;
32
- label: string;
33
- value: string;
34
- }
35
-
36
- interface HeaderTemplate {
37
- id: string;
38
- label: string;
39
- description: string;
40
- headers: Record<string, string>;
41
- }
42
-
43
- function getHeaderTemplates(): HeaderTemplate[] {
44
- return [
45
- {
46
- id: "codex-cli",
47
- label: "Codex",
48
- description: t("OpenAI 兼容端点使用的终端 Codex TUI 请求头。"),
49
- headers: CODEX_CLI_CLIENT_HEADERS,
50
- },
51
- {
52
- id: "claude-code",
53
- label: "ClaudeCode",
54
- description: t("Anthropic 兼容端点常用的 ClaudeCode 请求头。"),
55
- headers: CLAUDE_CODE_CLIENT_HEADERS,
56
- },
57
- {
58
- id: "empty",
59
- label: t("清空"),
60
- description: t("清空当前请求头,重新手动填写。"),
61
- headers: {},
62
- },
63
- ];
64
- }
65
-
66
- function buildProfileRows(document: StateDocument, profileIds: string[]): ProfileRow[] {
67
- return profileIds.map((profileId) => {
68
- const profile = document.requestHeaderProfiles[profileId]!;
69
- const usedCount = countModelsUsingRequestHeaderProfile(document, profileId);
70
- const label = formatProfileRow(profileId, profile, usedCount);
71
- return { profileId, label, usedCount, searchText: `${profileId} ${profile.name} ${label}` };
72
- });
73
- }
74
-
75
- function formatCapturedAt(capturedAt: string): string {
76
- return capturedAt.replace("T", " ").replace(/\.\d{3}Z$/, "Z").slice(0, 19);
77
- }
78
-
79
- function formatCaptureLine(label: string, capture: StoredClientHeaderCapture | undefined): string {
80
- if (!capture) return ` ${padLabel(label, 12)} ${t("未抓包")}`;
81
- return ` ${padLabel(label, 12)} ${t("已抓包 {time} · {count} headers", { time: formatCapturedAt(capture.capturedAt), count: Object.keys(capture.headers).length })}`;
82
- }
83
-
84
- interface ProfileTableCells {
85
- profileId: string;
86
- headers: string;
87
- used: string;
88
- name: string;
89
- }
90
-
91
- function formatProfileTableRow(cells: ProfileTableCells, availableWidth: number): string {
92
- if (availableWidth >= 64) {
93
- return [
94
- fitColumn(cells.profileId, 22),
95
- fitColumn(cells.headers, 12),
96
- fitColumn(cells.used, 10),
97
- fitColumn(cells.name, Math.max(10, availableWidth - 47)),
98
- ].join(" ");
99
- }
100
- if (availableWidth >= 46) {
101
- return [fitColumn(cells.profileId, 22), fitColumn(cells.headers, 12), fitColumn(cells.used, 10)].join(" ");
102
- }
103
- if (availableWidth >= 33) {
104
- return [fitColumn(cells.profileId, 20), fitColumn(cells.headers, 12)].join(" ");
105
- }
106
- return [
107
- fitColumn(cells.profileId, Math.max(8, availableWidth - 11)),
108
- fitColumn(cells.headers, 10),
109
- ].join(" ");
110
- }
111
-
112
- function formatProfileRow(
113
- profileId: string,
114
- profile: StoredRequestHeaderProfile,
115
- usedCount: number,
116
- availableWidth = 78,
117
- ): string {
118
- return formatProfileTableRow({
119
- profileId,
120
- headers: `${Object.keys(profile.headers).length} headers`,
121
- used: `${usedCount} models`,
122
- name: profile.name,
123
- }, availableWidth);
124
- }
125
-
126
- function formatProfileTableHeader(menuWidth: number): string {
127
- return ` ${formatProfileTableRow({
128
- profileId: t("自定义 ID"),
129
- headers: "Headers",
130
- used: "Used",
131
- name: t("名称"),
132
- }, Math.max(0, menuWidth - 2))}`;
133
- }
134
-
135
- function formatProfileDetailLines(
136
- profileId: string,
137
- profile: StoredRequestHeaderProfile,
138
- usedCount: number,
139
- theme?: Theme,
140
- ): string[] {
141
- const headerNames = Object.keys(profile.headers);
142
- const preview = headerNames.length > 0
143
- ? headerNames.slice(0, 6).join(", ") + (headerNames.length > 6 ? ", ..." : "")
144
- : "<empty>";
145
- return [
146
- formatDetailTitle(`${profile.name} (${profileId})`, theme),
147
- formatDetailField("usage", `${usedCount} models`, theme),
148
- formatDetailField("headers", preview, theme),
149
- ];
150
- }
151
-
152
- function buildEditorRows(draft: RequestHeaderProfileDraft): FieldRow[] {
153
- return [
154
- { id: "profileId", label: t("请求头 ID"), value: draft.profileId || t("<未填写>") },
155
- { id: "profileName", label: t("请求头名称"), value: draft.profileName || t("<未填写>") },
156
- { id: "template", label: t("快速模板"), value: t("选择后填充") },
157
- { id: "headers", label: t("请求头 JSON"), value: Object.keys(draft.headers).length > 0 ? t("{count}项", { count: Object.keys(draft.headers).length }) : t("未配置") },
158
- ];
159
- }
160
-
161
- function notifyValidationErrors(ctx: ExtensionCommandContext, errors: string[]): void {
162
- ctx.ui.notify(t("请求头无效:\n{errors}", { errors: errors.map((error) => `- ${error}`).join("\n") }), "warning");
163
- }
164
-
165
- function formatHeadersEditorText(headers: Record<string, string>): string {
166
- if (Object.keys(headers).length > 0) return JSON.stringify(headers, null, 2);
167
- return `{
168
- // ${t("可先返回上一级选择“快速模板”,也可在这里填写:")}
169
- // "user-agent": "custom-client/1.0"
170
- }
171
- `;
172
- }
173
-
174
- async function editHeaders(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft): Promise<void> {
175
- ctx.ui.notify(t("结构:JSON 对象;key 是客户端 header 名,value 是字符串。复杂示例请用“快速模板”。"), "info");
176
- while (true) {
177
- const answer = await ctx.ui.editor(t("请求头 JSON"), formatHeadersEditorText(draft.headers));
178
- if (answer === undefined) return;
179
- try {
180
- draft.headers = parseStringRecordJson(answer, t("请求头"));
181
- return;
182
- } catch (error) {
183
- ctx.ui.notify(t("请求头 JSON 无效:{error}", { error: formatUnknownError(error) }), "warning");
184
- }
185
- }
186
- }
187
-
188
- async function applyTemplate(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft): Promise<void> {
189
- const templates = getHeaderTemplates();
190
- const labels = templates.map((template) => `${template.label} — ${template.description}`);
191
- const picked = await ctx.ui.select(t("选择请求头模板"), labels);
192
- if (!picked) return;
193
- const index = labels.indexOf(picked);
194
- if (index < 0) return;
195
- const template = templates[index]!;
196
- draft.headers = { ...template.headers };
197
- ctx.ui.notify(
198
- template.id === "empty"
199
- ? t("已清空请求头")
200
- : t("已填充模板:{template},可继续进入“请求头 JSON”微调。", { template: template.label }),
201
- "info",
202
- );
203
- }
204
-
205
- async function editField(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft, fieldId: string): Promise<void> {
206
- if (fieldId === "profileId") {
207
- const value = await ctx.ui.input(t("请求头 ID(接入引用这个 ID;字母/数字/._-)"), draft.profileId);
208
- if (value !== undefined) draft.profileId = value.trim();
209
- return;
210
- }
211
- if (fieldId === "profileName") {
212
- const value = await ctx.ui.input(t("请求头名称(显示用)"), draft.profileName);
213
- if (value !== undefined) draft.profileName = value.trim();
214
- return;
215
- }
216
- if (fieldId === "template") {
217
- await applyTemplate(ctx, draft);
218
- return;
219
- }
220
- if (fieldId === "headers") {
221
- await editHeaders(ctx, draft);
222
- return;
223
- }
224
- }
225
-
226
- async function editProfile(
227
- ctx: ExtensionCommandContext,
228
- draft: RequestHeaderProfileDraft,
229
- titlePrefix: string,
230
- ): Promise<{ action: "save"; draft: RequestHeaderProfileDraft } | { action: "cancel" }> {
231
- const cursor: MenuCursor = { index: 0 };
232
- while (true) {
233
- const rows = buildEditorRows(draft);
234
- const menuRows = rows.map((row) => ({ id: row.id, label: `${padLabel(row.label, 16)}${row.value}` }));
235
- const action = await showPersistentFormMenu(
236
- ctx,
237
- titlePrefix,
238
- "",
239
- menuRows,
240
- cursor,
241
- {
242
- summaryLines: [
243
- t("认证类敏感 header 会被拒绝;API key 请放在接入配置中"),
244
- ],
245
- hints: [
246
- { key: "↑↓", label: t("选择") },
247
- { key: "Enter", label: t("编辑") },
248
- { key: "Ctrl+S", label: t("保存并同步") },
249
- { key: "Esc", label: t("返回") },
250
- ],
251
- },
252
- );
253
- if (action.type === "cancel") return { action: "cancel" };
254
- if (action.type === "save") return { action: "save", draft };
255
- await editField(ctx, draft, action.id);
256
- }
257
- }
258
-
259
- async function saveProfile(
260
- pi: ExtensionAPI,
261
- ctx: ExtensionCommandContext,
262
- draft: RequestHeaderProfileDraft,
263
- oldProfileId: string | undefined,
264
- ): Promise<boolean> {
265
- try {
266
- const state = await readState();
267
- const errors = validateRequestHeaderProfileDraft(draft, state, oldProfileId);
268
- if (errors.length > 0) {
269
- notifyValidationErrors(ctx, errors);
270
- return false;
271
- }
272
- await saveRequestHeaderProfileConfiguration(pi, ctx, state, draft, oldProfileId);
273
- } catch (error) {
274
- ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
275
- return false;
276
- }
277
- // [喵喵喵]: 保存后重新计数——重命名场景下引用已改指向新 ID,用保存前状态会误判 (issue #1);
278
- // 提示属于锦上添花,读取失败不能反向误导成保存失败
279
- try {
280
- const savedState = await readState();
281
- if (countModelsUsingRequestHeaderProfile(savedState, draft.profileId.trim()) === 0) {
282
- ctx.ui.notify(t("请求头 {profileId} 尚未被任何接入使用;在接入编辑器的「请求头」行选择后才会生效。", { profileId: draft.profileId.trim() }), "info");
283
- }
284
- } catch {
285
- // 计数提示失败时静默跳过,保存结果不受影响
286
- }
287
- return true;
288
- }
289
-
290
- async function deleteProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext, profileId: string): Promise<boolean> {
291
- const state = await readState();
292
- const profile = state.requestHeaderProfiles[profileId];
293
- if (!profile) {
294
- ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
295
- return true;
296
- }
297
- const affected = countModelsUsingRequestHeaderProfile(state, profileId);
298
- const ok = await ctx.ui.confirm(
299
- t("删除请求头 {profileId}", { profileId }),
300
- t("将删除 {name}。{affected}", {
301
- name: profile.name,
302
- affected: affected > 0 ? t("\n{count} 个模型会自动改回“自动推荐”。", { count: affected }) : "",
303
- }),
304
- );
305
- if (!ok) return false;
306
- try {
307
- await deleteRequestHeaderProfileConfiguration(pi, ctx, state, profileId);
308
- return true;
309
- } catch (error) {
310
- ctx.ui.notify(t("删除失败:{error}", { error: formatUnknownError(error) }), "error");
311
- return false;
312
- }
313
- }
314
-
315
- async function editStoredProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext, profileId: string): Promise<boolean> {
316
- const state = await readState();
317
- const profile = state.requestHeaderProfiles[profileId];
318
- if (!profile) {
319
- ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
320
- return true;
321
- }
322
- const draft = createRequestHeaderProfileDraftFromStored(profileId, profile);
323
- // [喵喵喵]: 保存失败时保留当前草稿重试,防止用户输入的头信息与名称被强制退出丢弃
324
- while (true) {
325
- const outcome = await editProfile(ctx, draft, t("编辑请求头 {profileId}", { profileId }));
326
- if (outcome.action !== "save") return false;
327
- const saved = await saveProfile(pi, ctx, outcome.draft, profileId);
328
- if (saved) return true;
329
- }
330
- }
331
-
332
- type HeaderProfileShortcut = "new-profile" | "delete-profile";
333
-
334
- export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
335
- const cursor: MenuCursor = { index: 0 };
336
- while (true) {
337
- const state = await readState();
338
- const profileIds = Object.keys(state.requestHeaderProfiles).sort((a, b) => a.localeCompare(b));
339
- const rows = buildProfileRows(state, profileIds);
340
- const action = await showPersistentShortcutMenu<HeaderProfileShortcut>(
341
- ctx,
342
- t("/model-manager / 请求头"),
343
- "",
344
- rows.map((row, index) => ({ id: `${index}`, label: row.label, searchText: row.searchText })),
345
- cursor,
346
- [
347
- { input: "n", shortcut: "new-profile" },
348
- { input: "d", shortcut: "delete-profile" },
349
- ],
350
- {
351
- summaryLines: [
352
- "Built-in captures",
353
- formatCaptureLine("ClaudeCode", state.clientHeaderCaptures["claude-code"]),
354
- formatCaptureLine("Codex", state.clientHeaderCaptures["codex-cli"]),
355
- `Custom profiles: ${rows.length}`,
356
- ],
357
- tableHeader: formatProfileTableHeader,
358
- formatRow: (menuRow, width) => {
359
- const row = rows[Number.parseInt(menuRow.id, 10)];
360
- const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
361
- return row && profile
362
- ? formatProfileRow(row.profileId, profile, row.usedCount, width)
363
- : menuRow.label;
364
- },
365
- getDetailLines: (selectedRow, theme) => {
366
- const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
367
- const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
368
- return row && profile
369
- ? formatProfileDetailLines(row.profileId, profile, row.usedCount, theme)
370
- : [];
371
- },
372
- hints: [
373
- { key: "↑↓", label: t("选择") },
374
- { key: "Enter", label: t("编辑请求头") },
375
- { key: "N", label: t("新建自定义") },
376
- { key: "D", label: t("删除") },
377
- { key: "Esc", label: t("返回") },
378
- ],
379
- emptyLabel: t("暂无自定义请求头;按 n 新建"),
380
- },
381
- );
382
- if (action.type === "cancel") return;
383
- if (action.type === "shortcut") {
384
- if (action.shortcut === "new-profile") {
385
- const draft = createRequestHeaderProfileDraft(profileIds);
386
- // [喵喵喵]: 新建保存失败时保留已输入的草稿继续编辑
387
- while (true) {
388
- const outcome = await editProfile(ctx, draft, t("新建请求头"));
389
- if (outcome.action !== "save") break;
390
- const saved = await saveProfile(pi, ctx, outcome.draft, undefined);
391
- if (saved) break;
392
- }
393
- continue;
394
- }
395
- const selectedProfileId = rows[cursor.index]?.profileId;
396
- if (!selectedProfileId) {
397
- ctx.ui.notify(t("没有可删除的请求头。"), "info");
398
- continue;
399
- }
400
- await deleteProfile(pi, ctx, selectedProfileId);
401
- continue;
402
- }
403
- const row = rows[Number.parseInt(action.id, 10)];
404
- if (!row) return;
405
- await editStoredProfile(pi, ctx, row.profileId);
406
- }
407
- }
@@ -1,273 +0,0 @@
1
- // tui/model-picker.ts
2
- //
3
- // 已拉取模型列表的本地选择器:8 行分页 + 直接输入搜索 + 匹配排序。
4
-
5
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
6
- import { CURSOR_MARKER, Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
7
- import { t } from "../i18n.ts";
8
- import { padLabel } from "./persistent-menu.ts";
9
-
10
- const MODEL_PAGE_SIZE = 8;
11
- const EXACT_MATCH_SCORE = 50_000;
12
- const PREFIX_MATCH_SCORE = 40_000;
13
- const SEGMENT_PREFIX_MATCH_SCORE = 30_000;
14
- const SUBSTRING_MATCH_SCORE = 20_000;
15
- const FUZZY_MATCH_SCORE = 10_000;
16
-
17
- interface RankedModelId {
18
- modelId: string;
19
- score: number;
20
- }
21
-
22
- function clampSelectedIndex(index: number, modelCount: number): number {
23
- if (modelCount <= 0) return 0;
24
- return Math.min(Math.max(0, index), modelCount - 1);
25
- }
26
-
27
- function getPageCount(modelCount: number): number {
28
- if (modelCount <= 0) return 0;
29
- return Math.ceil(modelCount / MODEL_PAGE_SIZE);
30
- }
31
-
32
- function getPageStart(selectedIndex: number): number {
33
- return Math.floor(selectedIndex / MODEL_PAGE_SIZE) * MODEL_PAGE_SIZE;
34
- }
35
-
36
- function normalizeSearchText(text: string): string {
37
- return text.trim().toLowerCase();
38
- }
39
-
40
- function splitSearchTokens(searchText: string): string[] {
41
- const normalized = normalizeSearchText(searchText);
42
- if (!normalized) return [];
43
- return normalized.split(/\s+/).filter(Boolean);
44
- }
45
-
46
- function splitModelSegments(normalizedModelId: string): string[] {
47
- return normalizedModelId.split(/[\s/:._-]+/).filter(Boolean);
48
- }
49
-
50
- function getFuzzySpan(normalizedModelId: string, token: string): number | undefined {
51
- let searchStart = 0;
52
- let firstMatchIndex = -1;
53
- let lastMatchIndex = -1;
54
- for (const character of token) {
55
- const matchIndex = normalizedModelId.indexOf(character, searchStart);
56
- if (matchIndex < 0) return undefined;
57
- if (firstMatchIndex < 0) firstMatchIndex = matchIndex;
58
- lastMatchIndex = matchIndex;
59
- searchStart = matchIndex + character.length;
60
- }
61
- return lastMatchIndex - firstMatchIndex + 1;
62
- }
63
-
64
- function rankTokenWithinModel(normalizedModelId: string, token: string): number | undefined {
65
- if (normalizedModelId === token) return EXACT_MATCH_SCORE;
66
- if (normalizedModelId.startsWith(token)) return PREFIX_MATCH_SCORE - normalizedModelId.length;
67
-
68
- const segmentIndex = splitModelSegments(normalizedModelId).findIndex((segment) => segment.startsWith(token));
69
- if (segmentIndex >= 0) {
70
- return SEGMENT_PREFIX_MATCH_SCORE - segmentIndex * 100 - normalizedModelId.length;
71
- }
72
-
73
- const substringIndex = normalizedModelId.indexOf(token);
74
- if (substringIndex >= 0) {
75
- return SUBSTRING_MATCH_SCORE - substringIndex * 100 - normalizedModelId.length;
76
- }
77
-
78
- const fuzzySpan = getFuzzySpan(normalizedModelId, token);
79
- if (fuzzySpan === undefined) return undefined;
80
- return FUZZY_MATCH_SCORE - fuzzySpan * 10 - normalizedModelId.length;
81
- }
82
-
83
- function rankModelId(modelId: string, searchText: string): number | undefined {
84
- const tokens = splitSearchTokens(searchText);
85
- if (tokens.length === 0) return 0;
86
-
87
- const normalizedModelId = modelId.toLowerCase();
88
- let combinedScore = 0;
89
- for (const token of tokens) {
90
- const tokenScore = rankTokenWithinModel(normalizedModelId, token);
91
- if (tokenScore === undefined) return undefined;
92
- combinedScore += tokenScore;
93
- }
94
- return combinedScore - normalizedModelId.length;
95
- }
96
-
97
- function sortModelIdsForSearch(modelIds: string[], searchText: string): string[] {
98
- const tokens = splitSearchTokens(searchText);
99
- if (tokens.length === 0) return [...modelIds].sort((a, b) => a.localeCompare(b));
100
-
101
- const rankedModelIds: RankedModelId[] = [];
102
- for (const modelId of modelIds) {
103
- const score = rankModelId(modelId, searchText);
104
- if (score !== undefined) rankedModelIds.push({ modelId, score });
105
- }
106
-
107
- rankedModelIds.sort((a, b) => {
108
- const scoreOrder = b.score - a.score;
109
- if (scoreOrder !== 0) return scoreOrder;
110
- const lengthOrder = a.modelId.length - b.modelId.length;
111
- if (lengthOrder !== 0) return lengthOrder;
112
- return a.modelId.localeCompare(b.modelId);
113
- });
114
- return rankedModelIds.map((model) => model.modelId);
115
- }
116
-
117
- function isPlainTextInput(data: string): boolean {
118
- if (!data) return false;
119
- for (const character of data) {
120
- const codePoint = character.codePointAt(0);
121
- if (codePoint === undefined || codePoint < 32 || codePoint === 127) return false;
122
- }
123
- return !data.includes("\x1b");
124
- }
125
-
126
- function formatPageText(modelCount: number, selectedIndex: number): string {
127
- const pageCount = getPageCount(modelCount);
128
- if (pageCount === 0) return t("页码 0 / 0");
129
- return t("页码 {page} / {pages}", { page: Math.floor(selectedIndex / MODEL_PAGE_SIZE) + 1, pages: pageCount });
130
- }
131
-
132
- export async function pickModelIdFromList(
133
- ctx: ExtensionCommandContext,
134
- title: string,
135
- modelIds: string[],
136
- currentModelId: string,
137
- ): Promise<string | undefined> {
138
- const sortedModelIds = [...new Set(modelIds)].sort((a, b) => a.localeCompare(b));
139
- const normalizedCurrentModelId = currentModelId.trim();
140
-
141
- return ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
142
- let searchText = "";
143
- let matchedModelIds = sortModelIdsForSearch(sortedModelIds, searchText);
144
- let selectedIndex = clampSelectedIndex(matchedModelIds.indexOf(normalizedCurrentModelId), matchedModelIds.length);
145
- let focused = false;
146
-
147
- const requestRender = (): void => {
148
- selectedIndex = clampSelectedIndex(selectedIndex, matchedModelIds.length);
149
- tui.requestRender();
150
- };
151
-
152
- const replaceSearchText = (nextSearchText: string): void => {
153
- searchText = nextSearchText;
154
- matchedModelIds = sortModelIdsForSearch(sortedModelIds, searchText);
155
- const selectedModelId = normalizeSearchText(searchText) ? undefined : normalizedCurrentModelId;
156
- const selectedModelIndex = selectedModelId ? matchedModelIds.indexOf(selectedModelId) : -1;
157
- selectedIndex = clampSelectedIndex(selectedModelIndex >= 0 ? selectedModelIndex : 0, matchedModelIds.length);
158
- requestRender();
159
- };
160
-
161
- const moveSelection = (delta: number): void => {
162
- selectedIndex = clampSelectedIndex(selectedIndex + delta, matchedModelIds.length);
163
- requestRender();
164
- };
165
-
166
- const movePage = (delta: number): void => {
167
- if (matchedModelIds.length === 0) return;
168
- const pageCount = getPageCount(matchedModelIds.length);
169
- const currentPageIndex = Math.floor(selectedIndex / MODEL_PAGE_SIZE);
170
- const rowOffset = selectedIndex % MODEL_PAGE_SIZE;
171
- const nextPageIndex = Math.min(Math.max(0, currentPageIndex + delta), pageCount - 1);
172
- selectedIndex = clampSelectedIndex(nextPageIndex * MODEL_PAGE_SIZE + rowOffset, matchedModelIds.length);
173
- requestRender();
174
- };
175
-
176
- return {
177
- get focused(): boolean {
178
- return focused;
179
- },
180
- set focused(value: boolean) {
181
- focused = value;
182
- },
183
- invalidate(): void {},
184
- handleInput(data: string): void {
185
- if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
186
- done(undefined);
187
- return;
188
- }
189
- if (matchesKey(data, Key.enter)) {
190
- const selectedModelId = matchedModelIds[selectedIndex];
191
- if (selectedModelId) done(selectedModelId);
192
- return;
193
- }
194
- if (matchesKey(data, Key.backspace)) {
195
- if (searchText.length > 0) replaceSearchText(Array.from(searchText).slice(0, -1).join(""));
196
- return;
197
- }
198
- if (matchesKey(data, Key.up)) {
199
- moveSelection(-1);
200
- return;
201
- }
202
- if (matchesKey(data, Key.down)) {
203
- moveSelection(1);
204
- return;
205
- }
206
- if (matchesKey(data, Key.pageUp) || matchesKey(data, Key.left)) {
207
- movePage(-1);
208
- return;
209
- }
210
- if (matchesKey(data, Key.pageDown) || matchesKey(data, Key.right)) {
211
- movePage(1);
212
- return;
213
- }
214
- if (matchesKey(data, Key.home)) {
215
- selectedIndex = 0;
216
- requestRender();
217
- return;
218
- }
219
- if (matchesKey(data, Key.end)) {
220
- selectedIndex = Math.max(0, matchedModelIds.length - 1);
221
- requestRender();
222
- return;
223
- }
224
- if (isPlainTextInput(data)) {
225
- replaceSearchText(searchText + data);
226
- }
227
- },
228
- render(width: number): string[] {
229
- selectedIndex = clampSelectedIndex(selectedIndex, matchedModelIds.length);
230
- const pageStart = getPageStart(selectedIndex);
231
- const visibleModelIds = matchedModelIds.slice(pageStart, pageStart + MODEL_PAGE_SIZE);
232
- const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
233
- const queryCursor = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
234
- const searchLine = searchText
235
- ? `${theme.fg("muted", t("搜索: "))}${searchText}${queryCursor}`
236
- : `${theme.fg("muted", t("搜索: "))}${queryCursor}${theme.fg("dim", t("<直接输入搜索>"))}`;
237
- const lines: string[] = [
238
- border,
239
- theme.fg("accent", theme.bold(title)),
240
- searchLine,
241
- theme.fg("dim", t("匹配 {matched} / {total} · {page}", {
242
- matched: matchedModelIds.length,
243
- total: sortedModelIds.length,
244
- page: formatPageText(matchedModelIds.length, selectedIndex),
245
- })),
246
- "",
247
- ];
248
-
249
- if (visibleModelIds.length === 0) {
250
- lines.push(theme.fg("warning", t("没有匹配模型;Backspace 删除搜索词,Esc 返回后可手动输入。")));
251
- } else {
252
- for (let rowIndex = 0; rowIndex < visibleModelIds.length; rowIndex += 1) {
253
- const absoluteIndex = pageStart + rowIndex;
254
- const modelId = visibleModelIds[rowIndex]!;
255
- const selected = absoluteIndex === selectedIndex;
256
- const currentSuffix = modelId === normalizedCurrentModelId ? theme.fg("dim", t(" ● 当前")) : "";
257
- const prefix = selected ? "❯ " : " ";
258
- const rowText = truncateToWidth(`${prefix}${modelId}${currentSuffix}`, width);
259
- // [喵喵喵]: 与列表菜单用同一种选中表现(背景色),避免两套选择器手感不一致。
260
- lines.push(selected ? theme.bg("selectedBg", padLabel(rowText, width)) : rowText);
261
- }
262
- }
263
-
264
- lines.push(
265
- "",
266
- theme.fg("dim", t("↑↓ 选择 · ←→/PgUp/PgDn 翻页 · 输入搜索 · Backspace 删除 · Enter 确认 · Esc 取消")),
267
- border,
268
- );
269
- return lines.map((line) => truncateToWidth(line, width));
270
- },
271
- };
272
- });
273
- }