@firstpick/pi-package-webui 0.10.1 → 0.10.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.10.1",
3
+ "version": "0.10.2",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/pi-coding-agent-forge/tree/main/pi-package-webui#readme",
@@ -72,7 +72,14 @@ test("native generation capabilities are extension-only and tab-local", () => {
72
72
 
73
73
  test("server dispatch requires extension provenance and completes on a fresh native artifact", () => {
74
74
  assert.match(server, /async function resolveGuidedGitNativeCommand[\s\S]*candidate\?\.source === "extension"[\s\S]*Same-named prompt templates are not used/u);
75
- assert.match(server, /record\.nativeCommandName = nativeCommandName;\s+record\.message = gitWorkflowGenerationPrompt\(kind, preferences, nativeCommandName\)/u);
75
+ const dispatchStart = server.indexOf("async function dispatchGitWorkflowGenerationAttempt");
76
+ const dispatchEnd = server.indexOf("\nasync function settleGitWorkflowGeneration", dispatchStart);
77
+ assert.notEqual(dispatchStart, -1);
78
+ assert.notEqual(dispatchEnd, -1);
79
+ const dispatch = server.slice(dispatchStart, dispatchEnd);
80
+ assert.match(dispatch, /record\.message = gitWorkflowGenerationPrompt\(record\.kind, record\.preferences, record\.nativeCommandName, profile\)/u);
81
+ assert.match(server, /record\.primary = gitWorkflowGenerationProfile\(\s+preferences\.generation\.provider,\s+preferences\.generation\.modelId,\s+preferences\.generation\.thinkingLevel,/u, "generation records should retain the configured profile used by dispatch");
82
+ assert.doesNotMatch(dispatch, /set_model|set_thinking_level|setThinkingLevelForTab/u, "guided generation must not switch or restore the parent tab model or reasoning effort");
76
83
  assert.match(server, /function guidedGitNativeCommandErrorFromEvent[\s\S]*event\?\.type !== "extension_error"[\s\S]*event\.extensionPath !== `command:\$\{commandName\}`/u);
77
84
  assert.match(server, /if \(record\.nativeCommandError\) throw record\.nativeCommandError;[\s\S]*await assertGuidedGitNativeArtifactUpdated\(tab, record\);[\s\S]*finishGitWorkflowGeneration\(tab, record, \{ successful: true \}\)/u);
78
85
  assert.match(server, /const target = path\.resolve\(base, `\$\{encodeURIComponent\(branch\)\}\.md`\)/u);
@@ -34,6 +34,13 @@ function writeBranchArtifact() {
34
34
  mkdirSync(directory, { recursive: true });
35
35
  writeFileSync(join(directory, "staged-branch-name.txt"), "feat/native-root-artifacts\\n");
36
36
  }
37
+ function generationProfile(message) {
38
+ const prefix = "--firstpick-webui-generation-profile=";
39
+ const token = String(message || "").split(/\\s+/u).find((part) => part.startsWith(prefix));
40
+ if (!token) return null;
41
+ try { return JSON.parse(Buffer.from(token.slice(prefix.length), "base64url").toString("utf8")); }
42
+ catch { return null; }
43
+ }
37
44
  function failNativeCommand(command, error, notificationError = error) {
38
45
  const commandName = String(command.message || "").split(/\\s+/u, 1)[0].replace(/^\\//u, "");
39
46
  send({
@@ -54,7 +61,16 @@ createInterface({ input: process.stdin }).on("line", async (line) => {
54
61
  let command;
55
62
  try { command = JSON.parse(line); } catch { return; }
56
63
  if (!command?.id || !command?.type) return;
57
- log({ type: command.type, modelId: command.modelId, level: command.level, message: command.message, activeModel: activeModel.id });
64
+ const profile = generationProfile(command.message);
65
+ log({
66
+ type: command.type,
67
+ modelId: command.modelId,
68
+ level: command.level,
69
+ message: command.message,
70
+ activeModel: activeModel.id,
71
+ generationModel: profile?.modelId,
72
+ generationThinkingLevel: profile?.thinkingLevel,
73
+ });
58
74
  const response = { type: "response", id: command.id, command: command.type, success: true };
59
75
  switch (command.type) {
60
76
  case "get_state":
@@ -84,7 +100,7 @@ createInterface({ input: process.stdin }).on("line", async (line) => {
84
100
  case "prompt":
85
101
  if (scenario === "process-loss") process.exit(12);
86
102
  if (scenario === "concurrent" || scenario === "cancellation") await new Promise((resolve) => setTimeout(resolve, 150));
87
- if (scenario === "provider-failure" && activeModel.id === "primary") {
103
+ if (scenario === "provider-failure" && profile?.modelId === "primary") {
88
104
  failNativeCommand(command, "FIRSTPICK_GUIDED_GIT_PROVIDER_FAILURE: active model generation failed", "The active model provider failed");
89
105
  send(response);
90
106
  break;
@@ -116,7 +132,7 @@ createInterface({ input: process.stdin }).on("line", async (line) => {
116
132
  }
117
133
  if (!["unsafe-stale-artifact", "cancellation"].includes(scenario)) {
118
134
  if (String(command.message || "").startsWith("/git-branch-name")) writeBranchArtifact();
119
- else writeCommitArtifacts(activeModel.id);
135
+ else writeCommitArtifacts(profile?.modelId || activeModel.id);
120
136
  }
121
137
  send({ ...response, data: { output: "native extension command completed" } });
122
138
  break;
@@ -238,7 +254,7 @@ try {
238
254
  await runScenario("success", async ({ request, readLog, cwd }) => {
239
255
  const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
240
256
  assert.equal(result.status, 200);
241
- assert.equal(result.body.data.message, "/git-staged-msg en auto");
257
+ assert.match(result.body.data.message, /^\/git-staged-msg en auto --firstpick-webui-generation-profile=/u);
242
258
  assert.equal(result.body.data.fallbackUsed, false);
243
259
  assert.equal(await readFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "utf8"), "feat: primary native generation\n");
244
260
  const correlated = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(result.body.data.generationId)}`);
@@ -246,9 +262,11 @@ try {
246
262
  const log = await readLog();
247
263
  assert.ok(log.some((entry) => entry.type === "get_commands"));
248
264
  assert.equal(log.filter((entry) => entry.type === "prompt").length, 1);
249
- const primary = log.findIndex((entry) => entry.type === "set_model" && entry.modelId === "primary");
250
- const restore = log.findIndex((entry) => entry.type === "set_model" && entry.modelId === "original");
251
- assert.ok(primary >= 0 && restore > primary, "the active model must be restored after native artifact verification");
265
+ const prompt = log.find((entry) => entry.type === "prompt");
266
+ assert.equal(prompt.activeModel, "original", "generation must not change the parent session model");
267
+ assert.equal(prompt.generationModel, "primary");
268
+ assert.equal(prompt.generationThinkingLevel, "low");
269
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
252
270
  });
253
271
 
254
272
  await runScenario("oversized-success", async ({ request, readLog, cwd }) => {
@@ -261,9 +279,9 @@ try {
261
279
  assert.equal(correlated.status, 200);
262
280
  assert.equal(correlated.body.data.ready, true);
263
281
  const log = await readLog();
264
- assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
265
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
266
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "original").length, 1);
282
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.generationModel), ["primary"]);
283
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["original"]);
284
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
267
285
  });
268
286
 
269
287
  await runScenario("nested-cwd", async ({ request, cwd, tabCwd }) => {
@@ -293,9 +311,10 @@ try {
293
311
  assert.equal(result.body.data.fallbackUsed, true);
294
312
  assert.equal(await readFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "utf8"), "feat: fallback native generation\n");
295
313
  const log = await readLog();
296
- assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary", "fallback"]);
297
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 1);
298
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "original").length, 1);
314
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.generationModel), ["primary", "fallback"]);
315
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.generationThinkingLevel), ["low", "off"]);
316
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["original", "original"]);
317
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
299
318
  });
300
319
 
301
320
  for (const [scenario, kind, expectedError] of [
@@ -312,8 +331,9 @@ try {
312
331
  assert.match(result.body.error, expectedError);
313
332
  if (scenario === "above-capture-input") assert.doesNotMatch(result.body.error, /message files? to be refreshed/iu);
314
333
  const log = await readLog();
315
- assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
316
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
334
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.generationModel), ["primary"]);
335
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["original"]);
336
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
317
337
  });
318
338
  }
319
339
 
@@ -325,16 +345,18 @@ try {
325
345
  assert.equal(cancelled.body.data.cancelled, true);
326
346
  assert.notEqual((await generation).status, 200);
327
347
  const log = await readLog();
328
- assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
329
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
348
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.generationModel), ["primary"]);
349
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["original"]);
350
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
330
351
  });
331
352
 
332
353
  await runScenario("process-loss", async ({ request, readLog }) => {
333
354
  const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
334
355
  assert.notEqual(result.status, 200);
335
356
  const log = await readLog();
336
- assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
337
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
357
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.generationModel), ["primary"]);
358
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["original"]);
359
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
338
360
  });
339
361
 
340
362
  await runScenario("prompt-only", async ({ request, readLog }) => {
@@ -342,7 +364,7 @@ try {
342
364
  assert.equal(result.status, 409);
343
365
  assert.match(result.body.error, /extension command.*Same-named prompt templates are not used/iu);
344
366
  const log = await readLog();
345
- assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "prompt").length, 0);
367
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level" || entry.type === "prompt").length, 0);
346
368
  });
347
369
 
348
370
  await runScenario("concurrent", async ({ request, readLog }) => {
@@ -351,7 +373,10 @@ try {
351
373
  request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } }),
352
374
  ]);
353
375
  assert.deepEqual([left.status, right.status].sort((a, b) => a - b), [200, 409]);
354
- assert.equal((await readLog()).filter((entry) => entry.type === "prompt").length, 1);
376
+ const log = await readLog();
377
+ assert.equal(log.filter((entry) => entry.type === "prompt").length, 1);
378
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["original"]);
379
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "set_thinking_level").length, 0);
355
380
  });
356
381
  } finally {
357
382
  await rm(temporaryRoot, { recursive: true, force: true });
@@ -51,7 +51,7 @@ assert.match(app, /generationKind: "commit"[\s\S]*generationKind: "branch"[\s\S]
51
51
  assert.match(app, /branch-name\$\{query\}[\s\S]*pr-description\$\{query\}/, "branch and PR artifact reads should send their exact generation IDs");
52
52
 
53
53
  assert.match(readme, /fallback model and its own reasoning effort[\s\S]*tries the fallback once[\s\S]*stopped Pi process do not trigger fallback/i, "README should explain the optional fallback and essential limits");
54
- assert.match(technical, /## Guided Git generation profiles[\s\S]*strict one-retry policy[\s\S]*model and reasoning effort are restored[\s\S]*dead Pi process cannot run the fallback/i, "technical reference should document configuration and operational limits");
54
+ assert.match(technical, /## Guided Git generation profiles[\s\S]*strict one-retry policy[\s\S]*active model and reasoning effort remain unchanged[\s\S]*dead Pi process cannot run the fallback/i, "technical reference should document configuration and operational limits");
55
55
  assert.match(development, /### Fallback browser\/runtime contract[\s\S]*fallbackUsed: true[\s\S]*webui_git_workflow_generation_fallback_started[\s\S]*never sends a retry/, "development guide should preserve the response/event and browser ownership contract");
56
56
 
57
57
  assert.match(html, /data-app-src="\/app\.js\?v=182"/, "the changed browser app should use the next query revision");
@@ -1895,9 +1895,10 @@ assert.match(app, /function cleanGitPublishVisibilityInput\(value\)[\s\S]*if \(v
1895
1895
  assert.doesNotMatch(app, /visibility = "(?:public|private)"/, "publication visibility should never be defaulted in the frontend");
1896
1896
  assert.match(server, /async function gitAddAllPayload\([\s\S]*platform\(\) === "win32"[\s\S]*findWindowsReservedGitPath\([\s\S]*windowsReservedGitPathFailure\(/, "guided git add should preflight Windows-reserved untracked paths before staging");
1897
1897
  assert.match(app, /Pre-commit verification reminder[\s\S]*Continue with this commit/, "configured verification reminders should run before committing");
1898
- assert.match(server, /async function startGitWorkflowGeneration\([\s\S]*set_model[\s\S]*setThinkingLevelForTab[\s\S]*type: "prompt"/, "server should apply the configured generation profile before prompting Pi");
1898
+ assert.match(server, /function gitWorkflowGenerationProfileArgument\(profile\)[\s\S]*--firstpick-webui-generation-profile=/, "server should encode the configured generation profile for the native extension command");
1899
+ assert.match(server, /async function dispatchGitWorkflowGenerationAttempt\([\s\S]*record\.message = gitWorkflowGenerationPrompt\(record\.kind, record\.preferences, record\.nativeCommandName, profile\)[\s\S]*type: "prompt"/, "server should dispatch the configured generation profile without changing the tab profile");
1899
1900
  assert.match(server, /function consumeGitWorkflowGenerationEvent\(tab, event[\s\S]*event\?\.type !== "agent_settled"[\s\S]*settleGitWorkflowGeneration\(tab, record, settlement\)/, "server should settle the owned Guided Git attempt only after agent settlement");
1900
- assert.match(server, /async function finishGitWorkflowGeneration\(tab, record[\s\S]*restoreGitWorkflowGenerationProfile\(tab, record\)/, "server should restore the active tab model and effort after Guided Git generation finishes");
1901
+ assert.match(server, /async function finishGitWorkflowGeneration\(tab, record[\s\S]*if \(tab\.gitWorkflowGeneration === record\) tab\.gitWorkflowGeneration = null;/, "server should finish Guided Git generation without restoring or changing the active tab model and effort");
1901
1902
  assert.match(server, /case "\/api\/git-workflow\/branch-name": \{[\s\S]*generationId[\s\S]*readGitWorkflowBranchName\(cwd, \{ generationId/, "server should expose exactly correlated generated branch-name loading for the guided PR workflow");
1902
1903
  assert.match(server, /case "\/api\/git-workflow\/branch":[\s\S]*createGitWorkflowBranchWorktree\(tab, body\)/, "server should route guided PR branch creation through worktree tabs");
1903
1904
  assert.match(server, /async function createGitWorkflowBranchWorktree\(tab, body = \{\}\)[\s\S]*expectedStagedContentHashFromBody\(body\)[\s\S]*snapshotGitWorkflowBranchState\(root, tab\.cwd, expectedStagedContentHash\)[\s\S]*applyGitWorkflowBranchStateToWorktree\(snapshot, worktreePath\)[\s\S]*openWorktreeResultForTab\(tab, createdResult/, "guided PR worktree creation should verify and copy exact staged state before opening the worktree tab");
@@ -2,23 +2,9 @@ import assert from "node:assert/strict";
2
2
  import { readFile } from "node:fs/promises";
3
3
 
4
4
  const source = await readFile(new URL("../index.ts", import.meta.url), "utf8");
5
- assert.match(source, /pi\.registerCommand\("tools"/);
6
- assert.match(source, /pi\.registerCommand\("skills"/);
7
- assert.doesNotMatch(
8
- source,
9
- /const runtimeToolBaseline\s*=\s*normalizeResourceNameList\(pi\.getActiveTools\(\)\)/,
10
- "extension action methods must not run while the extension factory is loading",
11
- );
12
- assert.match(source, /const runtimeTools = \(\): string\[\] => runtimeToolBaseline \?\?=/, "the tool baseline should be captured lazily after runtime binding");
13
- assert.match(source, /ctx\.mode !== "tui"/);
14
- assert.match(source, /pi\.on\("model_select"/);
15
- assert.match(source, /await recompute\(ctx, event\.model\)/, "model selection should immediately recompute exact-model resources");
16
- assert.match(source, /"Session only", "Global default", "Model default"/);
17
- assert.match(source, /"Use inherited defaults"/);
18
- assert.match(source, /selectTuiModelProfile\(ctx, \{/, "exact-model profiles should use the shared searchable model picker");
19
- assert.match(source, /selectTuiResources\(ctx, \{/, "resource lists should use the shared keyboard-driven selector");
20
- assert.match(source, /preserveUnavailableResourceNames\(/);
21
- assert.match(source, /setExactModelProfile\(/);
22
- assert.match(source, /skill\.disableModelInvocation !== true/);
5
+
6
+ assert.doesNotMatch(source, /pi\.registerCommand\("tools"/, "the tools extension must own /tools");
7
+ assert.doesNotMatch(source, /pi\.registerCommand\("skills"/, "the skills extension must own /skills");
8
+ assert.doesNotMatch(source, /registerTuiResourceController/, "WebUI must not manage TUI tool or skill state");
23
9
 
24
10
  console.log("resource-tui-extension.test.mjs passed");
@@ -1,183 +0,0 @@
1
- import { DynamicBorder } from "@earendil-works/pi-coding-agent";
2
- import { Container, fuzzyFilter, getKeybindings, Input, Key, matchesKey, Spacer, Text } from "@earendil-works/pi-tui";
3
-
4
- function modelKey(model) {
5
- return `${model.provider}\0${model.id}`;
6
- }
7
-
8
- function modelSearchText(model) {
9
- return `${model.provider} ${model.id} ${model.name || ""}`;
10
- }
11
-
12
- export class TuiModelProfileSelectorComponent extends Container {
13
- constructor(config, theme, callbacks) {
14
- super();
15
- const seen = new Set();
16
- this.models = config.models.filter((model) => {
17
- if (!model?.provider || !model?.id) return false;
18
- const key = modelKey(model);
19
- if (seen.has(key)) return false;
20
- seen.add(key);
21
- return true;
22
- });
23
- this.activeModelKey = config.activeModelKey || "";
24
- this.configuredModelKeys = new Set(config.configuredModelKeys || []);
25
- this.theme = theme;
26
- this.callbacks = callbacks;
27
- this.filteredModels = [...this.models];
28
- const activeModel = this.models.find((model) => modelKey(model) === this.activeModelKey);
29
- const configuredModel = this.models.find((model) => this.configuredModelKeys.has(modelKey(model)));
30
- const initialKey = activeModel ? this.activeModelKey : configuredModel ? modelKey(configuredModel) : "";
31
- this.selectedIndex = Math.max(0, this.filteredModels.findIndex((model) => modelKey(model) === initialKey));
32
- this.lastQuery = "";
33
- this.maxVisible = 10;
34
- this._focused = false;
35
-
36
- this.addChild(new DynamicBorder((text) => theme.fg("accent", text)));
37
- this.addChild(new Spacer(1));
38
- this.addChild(new Text(theme.fg("accent", theme.bold(config.title)), 0, 0));
39
- this.addChild(new Text(theme.fg("muted", config.subtitle), 0, 0));
40
- this.addChild(new Spacer(1));
41
-
42
- this.searchInput = new Input();
43
- this.addChild(this.searchInput);
44
- this.addChild(new Spacer(1));
45
-
46
- this.listContainer = new Container();
47
- this.addChild(this.listContainer);
48
- this.addChild(new Spacer(1));
49
-
50
- this.footerText = new Text(this.footer(), 0, 0);
51
- this.addChild(this.footerText);
52
- this.addChild(new DynamicBorder((text) => theme.fg("accent", text)));
53
- this.refresh();
54
- }
55
-
56
- get focused() {
57
- return this._focused;
58
- }
59
-
60
- set focused(value) {
61
- this._focused = value;
62
- this.searchInput.focused = value;
63
- }
64
-
65
- footer() {
66
- const position = this.filteredModels.length ? `${this.selectedIndex + 1}/${this.filteredModels.length}` : "0/0";
67
- return this.theme.fg("dim", ` ↑/↓ navigate · Enter select · Ctrl+C clear/cancel · Esc cancel · ${position}`);
68
- }
69
-
70
- refresh() {
71
- const selectedKey = this.filteredModels[this.selectedIndex] ? modelKey(this.filteredModels[this.selectedIndex]) : "";
72
- const query = this.searchInput.getValue();
73
- const queryChanged = query !== this.lastQuery;
74
- this.lastQuery = query;
75
- this.filteredModels = query ? fuzzyFilter(this.models, query, modelSearchText) : [...this.models];
76
- const retainedIndex = selectedKey
77
- ? this.filteredModels.findIndex((model) => modelKey(model) === selectedKey)
78
- : -1;
79
- this.selectedIndex = retainedIndex >= 0
80
- ? retainedIndex
81
- : queryChanged
82
- ? 0
83
- : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));
84
- this.updateList();
85
- this.footerText.setText(this.footer());
86
- this.callbacks.onRender?.();
87
- }
88
-
89
- updateList() {
90
- this.listContainer.clear();
91
- if (this.filteredModels.length === 0) {
92
- this.listContainer.addChild(new Text(this.theme.fg("muted", " No matching models"), 0, 0));
93
- return;
94
- }
95
-
96
- const startIndex = Math.max(
97
- 0,
98
- Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredModels.length - this.maxVisible),
99
- );
100
- const endIndex = Math.min(startIndex + this.maxVisible, this.filteredModels.length);
101
- for (let index = startIndex; index < endIndex; index++) {
102
- const model = this.filteredModels[index];
103
- const key = modelKey(model);
104
- const selected = index === this.selectedIndex;
105
- const prefix = selected ? this.theme.fg("accent", "→ ") : " ";
106
- const id = selected ? this.theme.fg("accent", model.id) : model.id;
107
- const provider = this.theme.fg("muted", ` [${model.provider}]`);
108
- const active = key === this.activeModelKey ? this.theme.fg("success", " [active]") : "";
109
- const configured = this.configuredModelKeys.has(key) ? this.theme.fg("warning", " [profile]") : "";
110
- this.listContainer.addChild(new Text(`${prefix}${id}${provider}${active}${configured}`, 0, 0));
111
- }
112
-
113
- if (startIndex > 0 || endIndex < this.filteredModels.length) {
114
- this.listContainer.addChild(
115
- new Text(this.theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredModels.length})`), 0, 0),
116
- );
117
- }
118
-
119
- const selectedModel = this.filteredModels[this.selectedIndex];
120
- if (selectedModel) {
121
- const profileState = this.configuredModelKeys.has(modelKey(selectedModel)) ? "configured" : "inherited";
122
- this.listContainer.addChild(new Spacer(1));
123
- this.listContainer.addChild(
124
- new Text(this.theme.fg("muted", ` Model Name: ${selectedModel.name || selectedModel.id} · Profile: ${profileState}`), 0, 0),
125
- );
126
- }
127
- }
128
-
129
- handleInput(data) {
130
- const keybindings = getKeybindings();
131
- if (keybindings.matches(data, "tui.select.up")) {
132
- if (this.filteredModels.length > 0) {
133
- this.selectedIndex = this.selectedIndex === 0 ? this.filteredModels.length - 1 : this.selectedIndex - 1;
134
- this.updateList();
135
- this.footerText.setText(this.footer());
136
- this.callbacks.onRender?.();
137
- }
138
- return;
139
- }
140
- if (keybindings.matches(data, "tui.select.down")) {
141
- if (this.filteredModels.length > 0) {
142
- this.selectedIndex = this.selectedIndex === this.filteredModels.length - 1 ? 0 : this.selectedIndex + 1;
143
- this.updateList();
144
- this.footerText.setText(this.footer());
145
- this.callbacks.onRender?.();
146
- }
147
- return;
148
- }
149
- if (keybindings.matches(data, "tui.select.confirm")) {
150
- const model = this.filteredModels[this.selectedIndex];
151
- if (model) this.callbacks.onSelect(model);
152
- return;
153
- }
154
- if (matchesKey(data, Key.ctrl("c"))) {
155
- if (this.searchInput.getValue()) {
156
- this.searchInput.setValue("");
157
- this.refresh();
158
- } else {
159
- this.callbacks.onCancel();
160
- }
161
- return;
162
- }
163
- if (matchesKey(data, Key.escape)) {
164
- this.callbacks.onCancel();
165
- return;
166
- }
167
-
168
- this.searchInput.handleInput(data);
169
- this.refresh();
170
- }
171
-
172
- getSearchInput() {
173
- return this.searchInput;
174
- }
175
- }
176
-
177
- export async function selectTuiModelProfile(ctx, config) {
178
- return await ctx.ui.custom((tui, theme, _keybindings, done) => new TuiModelProfileSelectorComponent(config, theme, {
179
- onSelect: done,
180
- onCancel: () => done(undefined),
181
- onRender: () => tui.requestRender(),
182
- }));
183
- }
@@ -1,173 +0,0 @@
1
- import { DynamicBorder } from "@earendil-works/pi-coding-agent";
2
- import { Container, fuzzyFilter, getKeybindings, Input, Key, matchesKey, Spacer, Text } from "@earendil-works/pi-tui";
3
-
4
- function keyMatches(data, keybinding, fallback) {
5
- const keybindings = getKeybindings();
6
- return keybindings.matches(data, keybinding) || matchesKey(data, fallback);
7
- }
8
-
9
- export class TuiResourceSelectorComponent extends Container {
10
- constructor(config, theme, callbacks) {
11
- super();
12
- this.resources = [...new Set(config.resources)];
13
- this.enabled = new Set(config.enabledResourceNames.filter((name) => this.resources.includes(name)));
14
- this.theme = theme;
15
- this.callbacks = callbacks;
16
- this.filteredResources = [...this.resources];
17
- this.selectedIndex = 0;
18
- this.maxVisible = 10;
19
- this.isDirty = false;
20
- this._focused = false;
21
-
22
- this.addChild(new DynamicBorder((text) => theme.fg("accent", text)));
23
- this.addChild(new Spacer(1));
24
- this.addChild(new Text(theme.fg("accent", theme.bold(config.title)), 0, 0));
25
- this.addChild(new Text(theme.fg("muted", config.subtitle), 0, 0));
26
- this.addChild(new Spacer(1));
27
-
28
- this.searchInput = new Input();
29
- this.addChild(this.searchInput);
30
- this.addChild(new Spacer(1));
31
-
32
- this.listContainer = new Container();
33
- this.addChild(this.listContainer);
34
- this.addChild(new Spacer(1));
35
-
36
- this.footerText = new Text(this.footer(), 0, 0);
37
- this.addChild(this.footerText);
38
- this.addChild(new DynamicBorder((text) => theme.fg("accent", text)));
39
- this.refresh();
40
- }
41
-
42
- get focused() {
43
- return this._focused;
44
- }
45
-
46
- set focused(value) {
47
- this._focused = value;
48
- this.searchInput.focused = value;
49
- }
50
-
51
- footer() {
52
- const text = ` Enter toggle · Ctrl+A all · Ctrl+X clear · Ctrl+S save · ${this.enabled.size}/${this.resources.length} enabled`;
53
- return this.isDirty ? `${this.theme.fg("dim", text)} ${this.theme.fg("warning", "(unsaved)")}` : this.theme.fg("dim", text);
54
- }
55
-
56
- refresh() {
57
- const query = this.searchInput.getValue();
58
- this.filteredResources = query ? fuzzyFilter(this.resources, query, (name) => name) : [...this.resources];
59
- this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredResources.length - 1));
60
- this.updateList();
61
- this.footerText.setText(this.footer());
62
- this.callbacks.onRender?.();
63
- }
64
-
65
- updateList() {
66
- this.listContainer.clear();
67
- if (this.filteredResources.length === 0) {
68
- this.listContainer.addChild(new Text(this.theme.fg("muted", " No matching resources"), 0, 0));
69
- return;
70
- }
71
-
72
- const startIndex = Math.max(
73
- 0,
74
- Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredResources.length - this.maxVisible),
75
- );
76
- const endIndex = Math.min(startIndex + this.maxVisible, this.filteredResources.length);
77
- for (let index = startIndex; index < endIndex; index++) {
78
- const name = this.filteredResources[index];
79
- const selected = index === this.selectedIndex;
80
- const prefix = selected ? this.theme.fg("accent", "→ ") : " ";
81
- const label = selected ? this.theme.fg("accent", name) : name;
82
- const status = this.enabled.has(name) ? this.theme.fg("success", " ✓") : this.theme.fg("dim", " ✗");
83
- this.listContainer.addChild(new Text(`${prefix}${label}${status}`, 0, 0));
84
- }
85
-
86
- if (startIndex > 0 || endIndex < this.filteredResources.length) {
87
- this.listContainer.addChild(
88
- new Text(this.theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredResources.length})`), 0, 0),
89
- );
90
- }
91
- }
92
-
93
- setFilteredEnabled(enabled) {
94
- const targets = this.searchInput.getValue() ? this.filteredResources : this.resources;
95
- for (const name of targets) {
96
- if (enabled) this.enabled.add(name);
97
- else this.enabled.delete(name);
98
- }
99
- this.isDirty = true;
100
- this.refresh();
101
- }
102
-
103
- handleInput(data) {
104
- const keybindings = getKeybindings();
105
-
106
- if (keybindings.matches(data, "tui.select.up")) {
107
- if (this.filteredResources.length > 0) {
108
- this.selectedIndex = this.selectedIndex === 0 ? this.filteredResources.length - 1 : this.selectedIndex - 1;
109
- this.updateList();
110
- this.callbacks.onRender?.();
111
- }
112
- return;
113
- }
114
- if (keybindings.matches(data, "tui.select.down")) {
115
- if (this.filteredResources.length > 0) {
116
- this.selectedIndex = this.selectedIndex === this.filteredResources.length - 1 ? 0 : this.selectedIndex + 1;
117
- this.updateList();
118
- this.callbacks.onRender?.();
119
- }
120
- return;
121
- }
122
- if (keybindings.matches(data, "tui.select.confirm")) {
123
- const name = this.filteredResources[this.selectedIndex];
124
- if (name) {
125
- if (this.enabled.has(name)) this.enabled.delete(name);
126
- else this.enabled.add(name);
127
- this.isDirty = true;
128
- this.refresh();
129
- }
130
- return;
131
- }
132
- if (keyMatches(data, "app.models.enableAll", Key.ctrl("a"))) {
133
- this.setFilteredEnabled(true);
134
- return;
135
- }
136
- if (keyMatches(data, "app.models.clearAll", Key.ctrl("x"))) {
137
- this.setFilteredEnabled(false);
138
- return;
139
- }
140
- if (keyMatches(data, "app.models.save", Key.ctrl("s"))) {
141
- this.callbacks.onSave(this.resources.filter((name) => this.enabled.has(name)));
142
- return;
143
- }
144
- if (matchesKey(data, Key.ctrl("c"))) {
145
- if (this.searchInput.getValue()) {
146
- this.searchInput.setValue("");
147
- this.refresh();
148
- } else {
149
- this.callbacks.onCancel();
150
- }
151
- return;
152
- }
153
- if (matchesKey(data, Key.escape)) {
154
- this.callbacks.onCancel();
155
- return;
156
- }
157
-
158
- this.searchInput.handleInput(data);
159
- this.refresh();
160
- }
161
-
162
- getSearchInput() {
163
- return this.searchInput;
164
- }
165
- }
166
-
167
- export async function selectTuiResources(ctx, config) {
168
- return await ctx.ui.custom((tui, theme, _keybindings, done) => new TuiResourceSelectorComponent(config, theme, {
169
- onSave: done,
170
- onCancel: () => done(undefined),
171
- onRender: () => tui.requestRender(),
172
- }));
173
- }