@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
290 lines • 13.7 kB
JavaScript
import { modelsAreEqual } from "@earendil-works/pi-ai";
import { Container, getKeybindings, Input, Key, matchesKey, Spacer, Text, TruncatedText, } from "@earendil-works/pi-tui";
import { rankModelSearchItems } from "../model-search-rank.js";
import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
import { keyText } from "./keybinding-hints.js";
import { clearFavoriteModels, favoriteModels, getModelFullId, getSortedFavoriteModelIds, isFavoriteModel, moveFavoriteModel, toggleFavoriteModel, } from "./model-favorites.js";
/**
* Component for managing favorite models for Ctrl+P cycling.
* Changes are session-only until explicitly persisted with Ctrl+S.
*/
export class FavoriteModelsSelectorComponent extends Container {
get focused() {
return this._focused;
}
set focused(value) {
this._focused = value;
this.searchInput.focused = value;
}
constructor(config, callbacks) {
super();
this.modelsById = new Map();
this.allIds = [];
this.favoriteIds = null;
/** Row order frozen at construction; membership toggles never move rows, only reorder keys do. */
this.displayIds = [];
this.filteredItems = [];
this.selectedIndex = 0;
// Focusable implementation - propagate to searchInput for IME cursor positioning
this._focused = false;
this.maxVisible = 8;
this.isDirty = false;
this.callbacks = callbacks;
this.currentModel = config.currentModel;
for (const model of config.allModels) {
const fullId = getModelFullId(model);
this.modelsById.set(fullId, model);
this.allIds.push(fullId);
}
this.favoriteIds = config.favoriteModelIds === null ? null : [...config.favoriteModelIds];
this.displayIds = getSortedFavoriteModelIds(this.favoriteIds, this.allIds);
this.filteredItems = this.buildItems();
// Header
this.addChild(new DynamicBorder());
this.addChild(new Spacer(1));
this.addChild(new Text(theme.fg("accent", theme.bold("Favorite Models")), 0, 0));
this.addChild(new Text(theme.fg("muted", `${keyText("tui.select.confirm")} selects. ${keyText("app.models.toggleFavorite")} toggles favorite. ${keyText("app.models.save")} saves.`), 0, 0));
this.addChild(new Spacer(1));
// Search input
this.searchInput = new Input();
this.addChild(this.searchInput);
this.addChild(new Spacer(1));
// List container
this.listContainer = new Container();
this.addChild(this.listContainer);
// Footer hint
this.addChild(new Spacer(1));
this.footerText = new Text(this.getFooterText(), 0, 0);
this.addChild(this.footerText);
this.secondaryFooterText = new Text(this.getSecondaryFooterText(), 0, 0);
this.addChild(this.secondaryFooterText);
this.addChild(new DynamicBorder());
this.updateList();
}
buildItems() {
// Filter out IDs that no longer have a corresponding model (e.g., after logout).
// Iterates the frozen displayIds snapshot; the favorite flag reads live membership.
const items = [];
for (const id of this.displayIds) {
const model = this.modelsById.get(id);
if (!model)
continue;
items.push({
fullId: id,
model,
favorite: isFavoriteModel(this.favoriteIds, id),
});
}
return items;
}
getFooterText() {
const favoriteCount = this.favoriteIds?.length ?? this.allIds.length;
const allFavorite = this.favoriteIds === null;
const countText = allFavorite ? "all favorites" : `${favoriteCount}/${this.allIds.length} favorites`;
const parts = [
`${keyText("tui.select.confirm")} select`,
`${keyText("app.models.toggleFavorite")} favorite`,
`${keyText("app.models.save")} save`,
countText,
];
return this.isDirty
? theme.fg("dim", ` ${parts.join(" · ")} `) + theme.fg("warning", "unsaved")
: theme.fg("dim", ` ${parts.join(" · ")}`);
}
getSecondaryFooterText() {
const parts = [
`${keyText("app.models.enableAll")} all`,
`${keyText("app.models.clearAll")} clear`,
`${keyText("app.models.toggleProvider")} provider`,
`${keyText("app.models.reorderUp")}/${keyText("app.models.reorderDown")} order`,
];
return theme.fg("dim", ` ${parts.join(" · ")}`);
}
refresh(preferredSelectedId) {
const query = this.searchInput.getValue();
const selectedId = preferredSelectedId ?? this.filteredItems[this.selectedIndex]?.fullId;
const items = this.buildItems();
// Management surface: relevance ranking without a favorites partition (empty query keeps base order).
this.filteredItems = rankModelSearchItems(items, query, (i) => ({ id: i.model.id, provider: i.model.provider, name: i.model.name }), { favoritesFirst: false, isFavorite: () => false });
const selectedIndex = selectedId ? this.filteredItems.findIndex((item) => item.fullId === selectedId) : -1;
this.selectedIndex =
selectedIndex >= 0 ? selectedIndex : Math.min(this.selectedIndex, Math.max(0, this.filteredItems.length - 1));
this.updateList();
this.footerText.setText(this.getFooterText());
this.secondaryFooterText.setText(this.getSecondaryFooterText());
}
/** Mirror a favoriteIds reorder swap onto the frozen display order so the row visibly moves. */
swapDisplayIds(firstId, secondId) {
const firstIndex = this.displayIds.indexOf(firstId);
const secondIndex = this.displayIds.indexOf(secondId);
if (firstIndex < 0 || secondIndex < 0)
return;
[this.displayIds[firstIndex], this.displayIds[secondIndex]] = [
this.displayIds[secondIndex],
this.displayIds[firstIndex],
];
}
notifyChange() {
this.callbacks.onChange(this.favoriteIds === null ? null : [...this.favoriteIds]);
}
updateList() {
this.listContainer.clear();
if (this.filteredItems.length === 0) {
this.listContainer.addChild(new Text(theme.fg("muted", " No matching models"), 0, 0));
return;
}
const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible));
const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);
for (let i = startIndex; i < endIndex; i++) {
const item = this.filteredItems[i];
if (!item)
continue;
const isSelected = i === this.selectedIndex;
const prefix = isSelected ? theme.fg("accent", "→ ") : " ";
const favoriteMarker = item.favorite ? theme.fg("success", "*") : theme.fg("dim", "-");
const modelText = isSelected ? theme.fg("accent", item.model.id) : item.model.id;
const providerBadge = theme.fg("muted", ` [${item.model.provider}]`);
const currentMarker = this.currentModel && modelsAreEqual(this.currentModel, item.model) ? theme.fg("success", " ✓") : "";
this.listContainer.addChild(new TruncatedText(`${prefix}${favoriteMarker} ${modelText}${providerBadge}${currentMarker}`));
}
// Add scroll indicator if needed
if (startIndex > 0 || endIndex < this.filteredItems.length) {
this.listContainer.addChild(new Text(theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredItems.length})`), 0, 0));
}
if (this.filteredItems.length > 0) {
const selected = this.filteredItems[this.selectedIndex];
if (selected) {
this.listContainer.addChild(new Spacer(1));
this.listContainer.addChild(new Text(theme.fg("muted", ` Model Name: ${selected.model.name}`), 0, 0));
}
}
}
handleInput(data) {
const kb = getKeybindings();
// Navigation
if (kb.matches(data, "tui.select.up")) {
if (this.filteredItems.length === 0)
return;
this.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;
this.updateList();
return;
}
if (kb.matches(data, "tui.select.down")) {
if (this.filteredItems.length === 0)
return;
this.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;
this.updateList();
return;
}
// Reorder favorite models
const reorderUp = kb.matches(data, "app.models.reorderUp");
const reorderDown = kb.matches(data, "app.models.reorderDown");
if (reorderUp || reorderDown) {
if (this.favoriteIds === null)
return;
const item = this.filteredItems[this.selectedIndex];
if (item && isFavoriteModel(this.favoriteIds, item.fullId)) {
const delta = reorderUp ? -1 : 1;
const currentIndex = this.favoriteIds.indexOf(item.fullId);
const newIndex = currentIndex + delta;
// Only move if within bounds
if (newIndex >= 0 && newIndex < this.favoriteIds.length) {
const displacedId = this.favoriteIds[newIndex];
this.favoriteIds = moveFavoriteModel(this.favoriteIds, item.fullId, delta);
this.swapDisplayIds(item.fullId, displacedId);
this.isDirty = true;
this.selectedIndex += delta;
this.refresh(item.fullId);
this.notifyChange();
}
}
return;
}
// Select on Enter
if (kb.matches(data, "tui.select.confirm")) {
const item = this.filteredItems[this.selectedIndex];
if (item) {
this.callbacks.onSelect(item.model);
}
return;
}
// Toggle favorite status for the selected model
if (kb.matches(data, "app.models.toggleFavorite")) {
const item = this.filteredItems[this.selectedIndex];
if (item) {
this.favoriteIds = toggleFavoriteModel(this.favoriteIds, this.allIds, item.fullId);
this.isDirty = true;
this.refresh(item.fullId);
this.notifyChange();
}
return;
}
// Favorite all (filtered if search active, otherwise all)
if (kb.matches(data, "app.models.enableAll")) {
const item = this.filteredItems[this.selectedIndex];
const targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;
this.favoriteIds = favoriteModels(this.favoriteIds, this.allIds, targetIds);
this.isDirty = true;
this.refresh(item?.fullId);
this.notifyChange();
return;
}
// Clear all (filtered if search active, otherwise all)
if (kb.matches(data, "app.models.clearAll")) {
const item = this.filteredItems[this.selectedIndex];
const targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;
this.favoriteIds = clearFavoriteModels(this.favoriteIds, this.allIds, targetIds);
this.isDirty = true;
this.refresh(item?.fullId);
this.notifyChange();
return;
}
// Toggle provider of current item
if (kb.matches(data, "app.models.toggleProvider")) {
const item = this.filteredItems[this.selectedIndex];
if (item) {
const provider = item.model.provider;
const providerIds = this.allIds.filter((id) => this.modelsById.get(id)?.provider === provider);
const allFavorite = providerIds.every((id) => isFavoriteModel(this.favoriteIds, id));
this.favoriteIds = allFavorite
? clearFavoriteModels(this.favoriteIds, this.allIds, providerIds)
: favoriteModels(this.favoriteIds, this.allIds, providerIds);
this.isDirty = true;
this.refresh(item.fullId);
this.notifyChange();
}
return;
}
// Save/persist to settings
if (kb.matches(data, "app.models.save")) {
this.callbacks.onPersist(this.favoriteIds === null ? null : [...this.favoriteIds]);
this.isDirty = false;
this.footerText.setText(this.getFooterText());
return;
}
// Ctrl+C - clear search or cancel if empty
if (matchesKey(data, Key.ctrl("c"))) {
if (this.searchInput.getValue()) {
this.searchInput.setValue("");
this.refresh();
}
else {
this.callbacks.onCancel();
}
return;
}
// Escape - cancel
if (matchesKey(data, Key.escape)) {
this.callbacks.onCancel();
return;
}
// Pass everything else to search input
this.searchInput.handleInput(data);
this.refresh();
}
getSearchInput() {
return this.searchInput;
}
}
//# sourceMappingURL=favorite-models-selector.js.map