pi-model-manager 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tui/dashboard.ts CHANGED
@@ -11,6 +11,8 @@
11
11
 
12
12
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
13
13
  import { formatUnknownError } from "../common.ts";
14
+ import { getUiLanguage, setUiLanguage, t, type UiLanguage } from "../i18n.ts";
15
+ import { writeUiLanguage } from "../ui-language-settings.ts";
14
16
  import {
15
17
  deleteModelConfiguration,
16
18
  deleteProviderConfiguration,
@@ -35,7 +37,7 @@ import { getBuiltinProviderIds } from "../builtin-model-catalog.ts";
35
37
  import type { StateDocument, StoredModel, StoredProvider } from "../types.ts";
36
38
  import { editModel } from "./editor-model.ts";
37
39
  import { editProvider } from "./editor-provider.ts";
38
- import { showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
40
+ import { showOptionPicker, showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
39
41
  import {
40
42
  formatModelListHeader,
41
43
  formatModelListRow,
@@ -44,47 +46,74 @@ import {
44
46
  formatProviderDetailLines,
45
47
  formatProviderEndpointLine,
46
48
  formatProviderSummaryLine,
49
+ getModelColumnWidths,
50
+ getProviderDisplayLabel,
51
+ getProviderNameColumnWidth,
47
52
  } from "./ui-helpers.ts";
48
53
  import { runHeaderProfilesPanel } from "./header-profiles-panel.ts";
49
54
 
50
55
  interface DashboardRow {
51
56
  providerId: string;
52
57
  label: string;
58
+ searchText: string;
53
59
  }
54
60
 
55
61
  interface ProviderMenuRow {
56
62
  modelId: string;
57
63
  model: StoredModel;
58
64
  label: string;
65
+ searchText: string;
59
66
  }
60
67
 
61
68
  function buildRows(document: StateDocument, builtInProviderIds: ReadonlySet<string>): DashboardRow[] {
62
69
  return Object.keys(document.providers)
63
70
  .filter((providerId) => !builtInProviderIds.has(providerId))
64
71
  .sort((a, b) => a.localeCompare(b))
65
- .map((providerId) => ({
66
- providerId,
67
- label: formatProviderConsoleRow(providerId, document.providers[providerId]!, document.requestHeaderProfiles),
68
- }));
72
+ .map((providerId) => {
73
+ const provider = document.providers[providerId]!;
74
+ const label = formatProviderConsoleRow(providerId, provider, 81, { requestHeaderProfiles: document.requestHeaderProfiles });
75
+ // [喵喵喵]: label 已被列宽截断,搜索需要补上完整的接入 ID 与名称。
76
+ return { providerId, label, searchText: `${providerId} ${getProviderDisplayName(providerId, provider)} ${label}` };
77
+ });
69
78
  }
70
79
 
71
80
  function buildProviderMenuRows(provider: StoredProvider): ProviderMenuRow[] {
72
81
  return [...provider.models]
73
82
  .sort((a, b) => a.id.localeCompare(b.id))
74
- .map((model) => ({
75
- modelId: model.id,
76
- model,
77
- label: formatModelListRow(provider, model),
78
- }));
83
+ .map((model) => {
84
+ const label = formatModelListRow(provider, model);
85
+ return { modelId: model.id, model, label, searchText: `${model.id} ${model.name ?? ""} ${label}` };
86
+ });
79
87
  }
80
88
 
81
89
  function notifyValidationErrors(ctx: ExtensionCommandContext, title: string, errors: string[]): void {
82
- ctx.ui.notify(`${title}:\n${errors.map((e) => `- ${e}`).join("\n")}`, "warning");
90
+ ctx.ui.notify(t("{title}:\n{errors}", { title, errors: errors.map((error) => `- ${error}`).join("\n") }), "warning");
83
91
  }
84
92
 
85
93
  async function confirmWarnings(ctx: ExtensionCommandContext, warnings: string[]): Promise<boolean> {
86
94
  if (warnings.length === 0) return true;
87
- return ctx.ui.confirm("请确认改动", `${warnings.join("\n")}\n\n继续保存?`);
95
+ return ctx.ui.confirm(t("请确认改动"), t("{warnings}\n\n继续保存?", { warnings: warnings.join("\n") }));
96
+ }
97
+
98
+ async function selectUiLanguage(ctx: ExtensionCommandContext): Promise<void> {
99
+ const currentLanguage = getUiLanguage();
100
+ const choice = await showOptionPicker<{ id: UiLanguage; label: string }>(
101
+ ctx,
102
+ "语言 / Language",
103
+ [
104
+ { id: "zh-CN", label: "简体中文 / Simplified Chinese" },
105
+ { id: "en", label: "English" },
106
+ ],
107
+ currentLanguage,
108
+ );
109
+ if (!choice || choice.id === currentLanguage) return;
110
+ try {
111
+ await writeUiLanguage(choice.id);
112
+ setUiLanguage(choice.id);
113
+ ctx.ui.notify(t("语言已切换为 {language}", { language: choice.id === "en" ? "English" : "简体中文" }), "info");
114
+ } catch (error) {
115
+ ctx.ui.notify(t("语言设置保存失败:{error}", { error: formatUnknownError(error) }), "error");
116
+ }
88
117
  }
89
118
 
90
119
 
@@ -100,7 +129,7 @@ async function saveProviderDraft(
100
129
  const builtInIds = await getBuiltinProviderIds();
101
130
  const errors = validateProviderDraft(draft, state, builtInIds, oldProviderId);
102
131
  if (errors.length > 0) {
103
- notifyValidationErrors(ctx, "接入配置无效", errors);
132
+ notifyValidationErrors(ctx, t("接入配置无效"), errors);
104
133
  return false;
105
134
  }
106
135
  const current = oldProviderId ? state.providers[oldProviderId] : state.providers[draft.providerId];
@@ -110,7 +139,7 @@ async function saveProviderDraft(
110
139
  await saveProviderConfiguration(pi, ctx, state, draft, oldProviderId);
111
140
  return true;
112
141
  } catch (error) {
113
- ctx.ui.notify(`保存失败:${formatUnknownError(error)}`, "error");
142
+ ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
114
143
  return false;
115
144
  }
116
145
  }
@@ -124,14 +153,14 @@ async function saveModelDraft(
124
153
  const state = await readState();
125
154
  const errors = validateModelDraft(draft, state, replacedModelId);
126
155
  if (errors.length > 0) {
127
- notifyValidationErrors(ctx, "模型配置无效", errors);
156
+ notifyValidationErrors(ctx, t("模型配置无效"), errors);
128
157
  return false;
129
158
  }
130
159
  try {
131
160
  await saveModelConfiguration(pi, ctx, state, draft, replacedModelId);
132
161
  return true;
133
162
  } catch (error) {
134
- ctx.ui.notify(`保存失败:${formatUnknownError(error)}`, "error");
163
+ ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
135
164
  return false;
136
165
  }
137
166
  }
@@ -146,20 +175,20 @@ async function saveNewProviderAndModelDraft(
146
175
  const builtInIds = await getBuiltinProviderIds();
147
176
  const providerErrors = validateProviderDraft(providerDraft, state, builtInIds, undefined);
148
177
  if (providerErrors.length > 0) {
149
- notifyValidationErrors(ctx, "接入配置无效", providerErrors);
178
+ notifyValidationErrors(ctx, t("接入配置无效"), providerErrors);
150
179
  return false;
151
180
  }
152
181
  const providerState = upsertProviderInDocument(state, undefined, providerDraft);
153
182
  const modelErrors = validateModelDraft(modelDraft, providerState, undefined);
154
183
  if (modelErrors.length > 0) {
155
- notifyValidationErrors(ctx, "模型配置无效", modelErrors);
184
+ notifyValidationErrors(ctx, t("模型配置无效"), modelErrors);
156
185
  return false;
157
186
  }
158
187
  try {
159
188
  await saveNewProviderWithModelConfiguration(pi, ctx, providerState, providerDraft, modelDraft);
160
189
  return true;
161
190
  } catch (error) {
162
- ctx.ui.notify(`保存失败:${formatUnknownError(error)}`, "error");
191
+ ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
163
192
  return false;
164
193
  }
165
194
  }
@@ -168,15 +197,15 @@ async function saveNewProviderAndModelDraft(
168
197
 
169
198
  async function deleteProvider(pi: ExtensionAPI, ctx: ExtensionCommandContext, providerId: string, provider: StoredProvider): Promise<boolean> {
170
199
  const ok = await ctx.ui.confirm(
171
- `删除接入 ${providerId}`,
172
- `将删除 ${getProviderDisplayName(providerId, provider)} 下全部 ${provider.models.length} 个模型。`,
200
+ t("删除接入 {providerId}", { providerId }),
201
+ t("将删除 {name} 下全部 {count} 个模型。", { name: getProviderDisplayName(providerId, provider), count: provider.models.length }),
173
202
  );
174
203
  if (!ok) return false;
175
204
  try {
176
205
  await deleteProviderConfiguration(pi, ctx, providerId, provider);
177
206
  return true;
178
207
  } catch (error) {
179
- ctx.ui.notify(`删除失败:${formatUnknownError(error)}`, "error");
208
+ ctx.ui.notify(t("删除失败:{error}", { error: formatUnknownError(error) }), "error");
180
209
  return false;
181
210
  }
182
211
  }
@@ -187,15 +216,15 @@ async function deleteModel(pi: ExtensionAPI, ctx: ExtensionCommandContext, provi
187
216
  const currentProvider = stateForPrompt.providers[providerId];
188
217
  const removesLastModel = (currentProvider?.models.length ?? 0) <= 1;
189
218
  const ok = await ctx.ui.confirm(
190
- `删除模型 ${fullId}`,
191
- removesLastModel ? "这是该接入下最后一个模型;删除后接入也会从 models.json 中移除。" : "只删除该模型,接入保留。",
219
+ t("删除模型 {fullId}", { fullId }),
220
+ removesLastModel ? t("这是该接入下最后一个模型;删除后接入也会从 models.json 中移除。") : t("只删除该模型,接入保留。"),
192
221
  );
193
222
  if (!ok) return false;
194
223
  try {
195
224
  await deleteModelConfiguration(pi, ctx, providerId, modelId);
196
225
  return true;
197
226
  } catch (error) {
198
- ctx.ui.notify(`删除失败:${formatUnknownError(error)}`, "error");
227
+ ctx.ui.notify(t("删除失败:{error}", { error: formatUnknownError(error) }), "error");
199
228
  return false;
200
229
  }
201
230
  }
@@ -215,11 +244,11 @@ async function editStoredModel(
215
244
  ): Promise<boolean> {
216
245
  const model = provider.models.find((m) => m.id === modelId);
217
246
  if (!model) {
218
- ctx.ui.notify(`模型不存在:${getModelFullId(providerId, modelId)}`, "error");
247
+ ctx.ui.notify(t("模型不存在:{fullId}", { fullId: getModelFullId(providerId, modelId) }), "error");
219
248
  return false;
220
249
  }
221
250
  const draft = createModelDraftFromStoredModel(providerId, provider, model);
222
- const outcome = await editModel(ctx, draft, `编辑模型 ${getModelFullId(providerId, modelId)}`, requestHeaderProfiles, clientHeaderCaptures);
251
+ const outcome = await editModel(ctx, draft, t("编辑模型 {fullId}", { fullId: getModelFullId(providerId, modelId) }), requestHeaderProfiles, clientHeaderCaptures);
223
252
  if (outcome.action !== "save") return false;
224
253
  return saveModelDraft(pi, ctx, outcome.draft, modelId);
225
254
  }
@@ -230,15 +259,16 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
230
259
  const state = await readState();
231
260
  const currentProvider = state.providers[providerId];
232
261
  if (!currentProvider) {
233
- ctx.ui.notify(`接入配置已不存在:${providerId}`, "warning");
262
+ ctx.ui.notify(t("接入配置已不存在:{providerId}", { providerId }), "warning");
234
263
  return true;
235
264
  }
236
265
  const rows = buildProviderMenuRows(currentProvider);
266
+ const modelColumns = getModelColumnWidths(currentProvider.models);
237
267
  const action = await showPersistentShortcutMenu<ProviderShortcut>(
238
268
  ctx,
239
269
  `/model-manager / ${getProviderDisplayName(providerId, currentProvider)}`,
240
270
  "",
241
- rows.map((row, index) => ({ id: `${index}`, label: row.label })),
271
+ rows.map((row, index) => ({ id: `${index}`, label: row.label, searchText: row.searchText })),
242
272
  cursor,
243
273
  [
244
274
  { input: "a", shortcut: "add-model" },
@@ -250,27 +280,34 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
250
280
  formatProviderSummaryLine(currentProvider, state.requestHeaderProfiles),
251
281
  formatProviderEndpointLine(currentProvider),
252
282
  ],
253
- tableHeader: (width) => formatModelListHeader(currentProvider, width),
254
- formatRow: (menuRow, width) => {
283
+ tableHeader: (width) => formatModelListHeader(currentProvider, width, modelColumns),
284
+ formatRow: (menuRow, width, theme) => {
255
285
  const row = rows[Number.parseInt(menuRow.id, 10)];
256
- return row ? formatModelListRow(currentProvider, row.model, width) : menuRow.label;
286
+ return row ? formatModelListRow(currentProvider, row.model, width, { ...modelColumns, theme }) : menuRow.label;
257
287
  },
258
288
  visibleRows: Math.min(12, Math.max(1, rows.length)),
259
- footer: "↑↓ 选择 Enter 编辑模型 a 添加模型 e 编辑接入 d 删除模型 Esc 返回",
260
- emptyLabel: "暂无模型;按 a 添加第一个模型",
289
+ hints: [
290
+ { key: "↑↓", label: t("选择") },
291
+ { key: "Enter", label: t("编辑模型") },
292
+ { key: "A", label: t("添加模型") },
293
+ { key: "E", label: t("编辑接入") },
294
+ { key: "D", label: t("删除模型") },
295
+ { key: "Esc", label: t("返回") },
296
+ ],
297
+ emptyLabel: t("暂无模型;按 a 添加第一个模型"),
261
298
  },
262
299
  );
263
300
  if (action.type === "cancel") return false;
264
301
  if (action.type === "shortcut") {
265
302
  if (action.shortcut === "add-model") {
266
303
  const draft = createModelDraftForStoredProvider(providerId, currentProvider);
267
- const outcome = await editModel(ctx, draft, `添加模型到 ${providerId}`, state.requestHeaderProfiles, state.clientHeaderCaptures);
304
+ const outcome = await editModel(ctx, draft, t("添加模型到 {providerId}", { providerId }), state.requestHeaderProfiles, state.clientHeaderCaptures);
268
305
  if (outcome.action === "save") await saveModelDraft(pi, ctx, outcome.draft, undefined);
269
306
  continue;
270
307
  }
271
308
  if (action.shortcut === "edit-provider") {
272
309
  const draft = createProviderDraftFromStored(providerId, currentProvider);
273
- const outcome = await editProvider(ctx, draft, `编辑接入 ${providerId}`, state.requestHeaderProfiles);
310
+ const outcome = await editProvider(ctx, draft, t("编辑接入 {providerId}", { providerId }), state.requestHeaderProfiles);
274
311
  if (outcome.action === "save") {
275
312
  await saveProviderDraft(pi, ctx, outcome.draft, providerId);
276
313
  if (outcome.draft.providerId !== providerId) return true;
@@ -279,7 +316,7 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
279
316
  }
280
317
  const selectedModelId = rows[cursor.index]?.modelId;
281
318
  if (!selectedModelId) {
282
- ctx.ui.notify("没有可删除的模型;删除接入请返回上一级按 d。", "info");
319
+ ctx.ui.notify(t("没有可删除的模型;删除接入请返回上一级按 d。"), "info");
283
320
  continue;
284
321
  }
285
322
  await deleteModel(pi, ctx, providerId, selectedModelId);
@@ -300,21 +337,21 @@ async function createProviderAndModel(pi: ExtensionAPI, ctx: ExtensionCommandCon
300
337
  const providerOutcome = await editProvider(
301
338
  ctx,
302
339
  providerDraft,
303
- "新建接入配置",
340
+ t("新建接入配置"),
304
341
  stateBeforeEdit.requestHeaderProfiles,
305
342
  );
306
343
  if (providerOutcome.action !== "save") return false;
307
344
  const providerErrors = validateProviderDraft(providerOutcome.draft, stateBeforeEdit, builtInIds, undefined);
308
345
  if (providerErrors.length > 0) {
309
- notifyValidationErrors(ctx, "接入配置无效", providerErrors);
346
+ notifyValidationErrors(ctx, t("接入配置无效"), providerErrors);
310
347
  continue;
311
348
  }
312
349
 
313
350
  const stagedState = upsertProviderInDocument(stateBeforeEdit, undefined, providerOutcome.draft);
314
351
  const stored = stagedState.providers[providerOutcome.draft.providerId]!;
315
- ctx.ui.notify("请继续添加第一个模型;取消模型编辑则不会创建该接入。", "info");
352
+ ctx.ui.notify(t("请继续添加第一个模型;取消模型编辑则不会创建该接入。"), "info");
316
353
  const modelDraft = createModelDraftForStoredProvider(providerOutcome.draft.providerId, stored);
317
- const modelOutcome = await editModel(ctx, modelDraft, `添加模型到 ${providerOutcome.draft.providerId}`, stagedState.requestHeaderProfiles, stagedState.clientHeaderCaptures);
354
+ const modelOutcome = await editModel(ctx, modelDraft, t("添加模型到 {providerId}", { providerId: providerOutcome.draft.providerId }), stagedState.requestHeaderProfiles, stagedState.clientHeaderCaptures);
318
355
  if (modelOutcome.action !== "save") return false;
319
356
  return saveNewProviderAndModelDraft(pi, ctx, providerOutcome.draft, modelOutcome.draft);
320
357
  }
@@ -322,7 +359,7 @@ async function createProviderAndModel(pi: ExtensionAPI, ctx: ExtensionCommandCon
322
359
 
323
360
  // ========== 入口 ==========
324
361
 
325
- type DashboardShortcut = "new-provider" | "header-profiles" | "delete-provider";
362
+ type DashboardShortcut = "new-provider" | "header-profiles" | "delete-provider" | "language";
326
363
 
327
364
  export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
328
365
  const cursor: MenuCursor = { index: 0 };
@@ -330,10 +367,13 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
330
367
  const state = await readState();
331
368
  const builtInProviderIds = await getBuiltinProviderIds();
332
369
  const rows = buildRows(state, builtInProviderIds);
370
+ const nameWidth = getProviderNameColumnWidth(
371
+ rows.map((row) => getProviderDisplayLabel(row.providerId, state.providers[row.providerId]!)),
372
+ );
333
373
  const modelCount = rows.reduce((sum, row) => sum + (state.providers[row.providerId]?.models.length ?? 0), 0);
334
374
  const profileCount = Object.keys(state.requestHeaderProfiles).length;
335
375
  const captureCount = Object.keys(state.clientHeaderCaptures).length;
336
- const menuRows = rows.map((r, index) => ({ id: `${index}`, label: r.label }));
376
+ const menuRows = rows.map((r, index) => ({ id: `${index}`, label: r.label, searchText: r.searchText }));
337
377
  const action = await showPersistentShortcutMenu<DashboardShortcut>(
338
378
  ctx,
339
379
  "/model-manager",
@@ -344,35 +384,52 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
344
384
  { input: "n", shortcut: "new-provider" },
345
385
  { input: "h", shortcut: "header-profiles" },
346
386
  { input: "d", shortcut: "delete-provider" },
387
+ { input: "l", shortcut: "language" },
347
388
  ],
348
389
  {
349
- summaryLines: [`${rows.length} 接入 · ${modelCount} 模型 · ${captureCount} 内置抓包 · ${profileCount} 自定义请求头`],
350
- tableHeader: formatProviderConsoleHeader,
351
- formatRow: (menuRow, width) => {
390
+ summaryLines: [t("{providers} 接入 · {models} 模型 · {captures} 内置抓包 · {profiles} 自定义请求头", {
391
+ providers: rows.length,
392
+ models: modelCount,
393
+ captures: captureCount,
394
+ profiles: profileCount,
395
+ })],
396
+ tableHeader: (width) => formatProviderConsoleHeader(width, { nameWidth }),
397
+ formatRow: (menuRow, width, theme) => {
352
398
  const row = rows[Number.parseInt(menuRow.id, 10)];
353
399
  const provider = row ? state.providers[row.providerId] : undefined;
354
400
  return row && provider
355
- ? formatProviderConsoleRow(row.providerId, provider, state.requestHeaderProfiles, width)
401
+ ? formatProviderConsoleRow(row.providerId, provider, width, { requestHeaderProfiles: state.requestHeaderProfiles, theme, nameWidth })
356
402
  : menuRow.label;
357
403
  },
358
- getDetailLines: (selectedRow) => {
404
+ getDetailLines: (selectedRow, theme) => {
359
405
  const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
360
406
  const provider = row ? state.providers[row.providerId] : undefined;
361
- return row && provider ? formatProviderDetailLines(row.providerId, provider, state.requestHeaderProfiles) : [];
407
+ return row && provider
408
+ ? formatProviderDetailLines(row.providerId, provider, { requestHeaderProfiles: state.requestHeaderProfiles, theme })
409
+ : [];
362
410
  },
363
- footer: "↑↓ 选择 Enter 进入 n 新建接入 d 删除接入 h 请求头 Esc 退出",
364
- emptyLabel: "暂无自定义接入;按 n 新建",
411
+ hints: [
412
+ { key: "↑↓", label: t("选择") },
413
+ { key: "Enter", label: t("进入") },
414
+ { key: "N", label: t("新建接入") },
415
+ { key: "D", label: t("删除接入") },
416
+ { key: "H", label: t("请求头管理") },
417
+ { key: "L", label: "语言 / Language" },
418
+ { key: "Esc", label: t("退出") },
419
+ ],
420
+ emptyLabel: t("暂无自定义接入;按 n 新建"),
365
421
  },
366
422
  );
367
423
  if (action.type === "cancel") return;
368
424
  if (action.type === "shortcut") {
369
425
  if (action.shortcut === "new-provider") await createProviderAndModel(pi, ctx);
370
426
  if (action.shortcut === "header-profiles") await runHeaderProfilesPanel(pi, ctx);
427
+ if (action.shortcut === "language") await selectUiLanguage(ctx);
371
428
  if (action.shortcut === "delete-provider") {
372
429
  const selectedProviderId = rows[cursor.index]?.providerId;
373
430
  const selectedProvider = selectedProviderId ? state.providers[selectedProviderId] : undefined;
374
431
  if (selectedProviderId && selectedProvider) await deleteProvider(pi, ctx, selectedProviderId, selectedProvider);
375
- else ctx.ui.notify("没有可删除的接入。", "info");
432
+ else ctx.ui.notify(t("没有可删除的接入。"), "info");
376
433
  }
377
434
  continue;
378
435
  }
@@ -381,7 +438,7 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
381
438
  const row = rows[index]!;
382
439
  const provider = state.providers[row.providerId];
383
440
  if (!provider) {
384
- ctx.ui.notify(`接入配置已不存在:${row.providerId}`, "warning");
441
+ ctx.ui.notify(t("接入配置已不存在:{providerId}", { providerId: row.providerId }), "warning");
385
442
  continue;
386
443
  }
387
444
  await showProviderMenu(pi, ctx, row.providerId);