Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

sort /model list by most-recently-used (#251)

ktda8565fca576
diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts
index a34798a2e8..567b417ff9 100644
--- a/packages/coding-agent/src/core/settings-manager.ts
+++ b/packages/coding-agent/src/core/settings-manager.ts
@@ -5,6 +5,8 @@ import { dirname, join } from "path";
import lockfile from "proper-lockfile";
import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
+const RECENT_MODELS_LIMIT = 20;
+
export interface CompactionSettings {
enabled?: boolean; // default: true
reserveTokens?: number; // default: 16384
@@ -77,6 +79,7 @@ export interface Settings {
onboardingCompleted?: boolean;
defaultProvider?: string;
defaultModel?: string;
+ recentModels?: string[]; // "provider/id" keys, most-recently-used first
defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
transport?: TransportSetting; // default: "auto"
steeringMode?: "all" | "one-at-a-time";
@@ -615,9 +618,21 @@ export class SettingsManager {
this.globalSettings.defaultModel = modelId;
this.markModified("defaultProvider");
this.markModified("defaultModel");
+ this.recordModelUseInternal(provider, modelId);
+ this.markModified("recentModels");
this.save();
}
+ getRecentModels(): string[] {
+ return this.settings.recentModels ?? [];
+ }
+
+ private recordModelUseInternal(provider: string, modelId: string): void {
+ const key = `${provider}/${modelId}`;
+ const next = [key, ...this.getRecentModels().filter((k) => k !== key)];
+ this.globalSettings.recentModels = next.slice(0, RECENT_MODELS_LIMIT);
+ }
+
getSteeringMode(): "all" | "one-at-a-time" {
return this.settings.steeringMode || "one-at-a-time";
}
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index 45395cc535..8fd2a214f5 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -888,7 +888,11 @@ class AgentsViewMode implements Component, Focusable {
resolve();
},
initialSearchInput,
- { availableModels, getRows: () => this.ui.terminal.rows },
+ {
+ availableModels,
+ getRows: () => this.ui.terminal.rows,
+ recentModels: this.options.uiServices.settingsManager.getRecentModels(),
+ },
);
handle = showFullPaneOverlay(this.ui, selector, 96);
});
diff --git a/packages/coding-agent/src/modes/interactive/components/model-selector.ts b/packages/coding-agent/src/modes/interactive/components/model-selector.ts
index b7eaa9aa59..7e93681f48 100644
--- a/packages/coding-agent/src/modes/interactive/components/model-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/model-selector.ts
@@ -1,5 +1,13 @@
import { type Model, modelsAreEqual } from "@earendil-works/pi-ai";
-import { Container, type Focusable, fuzzyFilter, getKeybindings, Spacer, Text, type TUI } from "@earendil-works/pi-tui";
+import {
+ Container,
+ type Focusable,
+ fuzzyFilterScored,
+ getKeybindings,
+ Spacer,
+ Text,
+ type TUI,
+} from "@earendil-works/pi-tui";
import type { ModelRegistry } from "../../../core/model-registry.js";
import { theme } from "../theme/theme.js";
import { keyHint, keyText } from "./keybinding-hints.js";
@@ -36,6 +44,7 @@ interface ModelSelectorOptions {
onAction?: (actionId: string) => void;
subtitle?: string;
getRows?: () => number;
+ recentModels?: ReadonlyArray<string>;
}
type ModelScope = "all" | "scoped";
@@ -77,6 +86,7 @@ export class ModelSelectorComponent extends Container implements Focusable {
private actions: ReadonlyArray<ModelSelectorAction>;
private availableModels?: ReadonlyArray<Model<any>>;
private onActionCallback?: (actionId: string) => void;
+ private recentRank: Map<string, number>;
private errorMessage?: string;
private tui: TUI;
private scopedModels: ReadonlyArray<ScopedModelItem>;
@@ -117,6 +127,7 @@ export class ModelSelectorComponent extends Container implements Focusable {
this.actions = options.actions ?? [];
this.availableModels = options.availableModels;
this.onActionCallback = options.onAction;
+ this.recentRank = new Map((options.recentModels ?? []).map((key, i) => [key, i]));
this.viewport = { getRows: options.getRows };
this.panel = new MenuPanel({
@@ -224,14 +235,20 @@ export class ModelSelectorComponent extends Container implements Focusable {
currentIndex >= 0 ? currentIndex : Math.min(this.selectedIndex, Math.max(0, this.getSelectableCount() - 1));
}
+ private recentRankOf(item: ModelItem): number {
+ // Finite sentinel so subtracting two non-recent ranks yields 0, not NaN.
+ return this.recentRank.get(`${item.provider}/${item.id}`) ?? Number.MAX_SAFE_INTEGER;
+ }
+
private sortModels(models: ModelItem[]): ModelItem[] {
const sorted = [...models];
- // Sort: current model first, then by provider
+ // Current model first, then most-recently-used, then provider.
sorted.sort((a, b) => {
const aIsCurrent = modelsAreEqual(this.currentModel, a.model);
const bIsCurrent = modelsAreEqual(this.currentModel, b.model);
- if (aIsCurrent && !bIsCurrent) return -1;
- if (!aIsCurrent && bIsCurrent) return 1;
+ if (aIsCurrent !== bIsCurrent) return aIsCurrent ? -1 : 1;
+ const rankDiff = this.recentRankOf(a) - this.recentRankOf(b);
+ if (rankDiff !== 0) return rankDiff;
return a.provider.localeCompare(b.provider);
});
return sorted;
@@ -260,13 +277,18 @@ export class ModelSelectorComponent extends Container implements Focusable {
}
private filterModels(query: string): void {
- this.filteredModels = query
- ? fuzzyFilter(
- this.activeModels,
- query,
- ({ id, provider }) => `${id} ${provider} ${provider}/${id} ${provider} ${id}`,
- )
- : this.activeModels;
+ if (query.trim()) {
+ const scored = fuzzyFilterScored(
+ this.activeModels,
+ query,
+ ({ id, provider }) => `${id} ${provider} ${provider}/${id} ${provider} ${id}`,
+ );
+ // Among equally-good matches (e.g. glm-5 / glm-5.1 / glm-5.2), prefer the most-recently-used.
+ scored.sort((a, b) => a.score - b.score || this.recentRankOf(a.item) - this.recentRankOf(b.item));
+ this.filteredModels = scored.map((r) => r.item);
+ } else {
+ this.filteredModels = this.activeModels;
+ }
this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.getSelectableCount() - 1));
this.updateList();
}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 4263a319ab..07a32ec1e1 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -5949,6 +5949,7 @@ export class InteractiveMode {
},
subtitle: options?.subtitle,
getRows: () => this.ui.terminal.rows,
+ recentModels: this.settingsManager.getRecentModels(),
},
);
handle = this.showFullPaneOverlay(selector, 96);
diff --git a/packages/coding-agent/test/model-selector-actions.test.ts b/packages/coding-agent/test/model-selector-actions.test.ts
index bd47951b50..afd6b1ccc5 100644
--- a/packages/coding-agent/test/model-selector-actions.test.ts
+++ b/packages/coding-agent/test/model-selector-actions.test.ts
@@ -138,6 +138,68 @@ describe("ModelSelectorComponent provider actions", () => {
expect(output).toContain("(2/12)");
});
+ it("orders search matches by recency among equally-good fuzzy matches", async () => {
+ const harness = await createHarness({
+ models: [
+ { id: "glm-5", name: "GLM 5", reasoning: true },
+ { id: "glm-5.1", name: "GLM 5.1", reasoning: true },
+ { id: "glm-5.2", name: "GLM 5.2", reasoning: true },
+ ],
+ });
+ harnesses.push(harness);
+
+ const provider = harness.getModel("glm-5")!.provider;
+ const selector = new ModelSelectorComponent(
+ createFakeTui(),
+ undefined,
+ harness.session.modelRegistry,
+ [],
+ () => {},
+ () => {},
+ "glm",
+ { recentModels: [`${provider}/glm-5.2`, `${provider}/glm-5.1`] },
+ );
+
+ await waitForAsyncRender();
+
+ const lines = stripAnsi(selector.render(120).join("\n")).split("\n");
+ const row52 = lines.findIndex((line) => /glm-5\.2/.test(line));
+ const row51 = lines.findIndex((line) => /glm-5\.1/.test(line));
+ const row5 = lines.findIndex((line) => /glm-5(?![.\d])/.test(line));
+ expect(row52).toBeGreaterThanOrEqual(0);
+ expect(row52).toBeLessThan(row51);
+ expect(row51).toBeLessThan(row5);
+ });
+
+ it("treats a whitespace-only query as no search and keeps the current model first", async () => {
+ const harness = await createHarness({
+ models: [
+ { id: "glm-5", name: "GLM 5", reasoning: true },
+ { id: "glm-5.1", name: "GLM 5.1", reasoning: true },
+ { id: "glm-5.2", name: "GLM 5.2", reasoning: true },
+ ],
+ });
+ harnesses.push(harness);
+
+ const provider = harness.getModel("glm-5")!.provider;
+ const selector = new ModelSelectorComponent(
+ createFakeTui(),
+ harness.getModel("glm-5"),
+ harness.session.modelRegistry,
+ [],
+ () => {},
+ () => {},
+ " ",
+ { recentModels: [`${provider}/glm-5.2`, `${provider}/glm-5.1`] },
+ );
+
+ await waitForAsyncRender();
+
+ const lines = stripAnsi(selector.render(120).join("\n")).split("\n");
+ const firstRow = lines.findIndex((line) => /glm-5/.test(line));
+ expect(/glm-5(?![.\d])/.test(lines[firstRow] ?? "")).toBe(true);
+ });
+
it("keeps scoped model help within a short terminal viewport", async () => {
const harness = await createHarness({
models: Array.from({ length: 12 }, (_, index) => ({
diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.ts
index dc4c93fcb4..2d2d15a3a5 100644
--- a/packages/coding-agent/test/settings-manager.test.ts
+++ b/packages/coding-agent/test/settings-manager.test.ts
@@ -212,6 +212,33 @@ describe("SettingsManager", () => {
});
});
+ describe("recentModels", () => {
+ it("records most-recently-used first, dedupes, and persists", async () => {
+ const manager = SettingsManager.create(projectDir, agentDir);
+
+ manager.setDefaultModelAndProvider("prov", "a");
+ manager.setDefaultModelAndProvider("prov", "b");
+ manager.setDefaultModelAndProvider("prov", "a");
+ await manager.flush();
+
+ expect(manager.getRecentModels()).toEqual(["prov/a", "prov/b"]);
+ const saved = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf-8"));
+ expect(saved.recentModels).toEqual(["prov/a", "prov/b"]);
+ });
+
+ it("caps the list at the limit", async () => {
+ const manager = SettingsManager.create(projectDir, agentDir);
+ for (let i = 0; i < 25; i++) {
+ manager.setDefaultModelAndProvider("prov", `m${i}`);
+ }
+ await manager.flush();
+
+ const recent = manager.getRecentModels();
+ expect(recent).toHaveLength(20);
+ expect(recent[0]).toBe("prov/m24");
+ });
+ });
+
describe("error tracking", () => {
it("should collect and clear load errors via drainErrors", () => {
const globalSettingsPath = join(agentDir, "settings.json");
diff --git a/packages/tui/src/fuzzy.ts b/packages/tui/src/fuzzy.ts
index 35df468a98..4a3557862c 100644
--- a/packages/tui/src/fuzzy.ts
+++ b/packages/tui/src/fuzzy.ts
@@ -92,25 +92,27 @@ export function fuzzyMatch(query: string, text: string): FuzzyMatch {
return { matches: true, score: swappedMatch.score + 5 };
}
+export interface ScoredItem<T> {
+ item: T;
+ score: number;
+}
+
/**
- * Filter and sort items by fuzzy match quality (best matches first).
- * Supports space-separated tokens: all tokens must match.
+ * Filter items by fuzzy match quality, returning each match with its score
+ * (lower is better) sorted best-first. Supports space-separated tokens: all
+ * tokens must match.
*/
-export function fuzzyFilter<T>(items: T[], query: string, getText: (item: T) => string): T[] {
- if (!query.trim()) {
- return items;
- }
-
+export function fuzzyFilterScored<T>(items: T[], query: string, getText: (item: T) => string): ScoredItem<T>[] {
const tokens = query
.trim()
.split(/\s+/)
.filter((t) => t.length > 0);
if (tokens.length === 0) {
- return items;
+ return items.map((item) => ({ item, score: 0 }));
}
- const results: { item: T; totalScore: number }[] = [];
+ const results: ScoredItem<T>[] = [];
for (const item of items) {
const text = getText(item);
@@ -128,10 +130,21 @@ export function fuzzyFilter<T>(items: T[], query: string, getText: (item: T) =>
}
if (allMatch) {
- results.push({ item, totalScore });
+ results.push({ item, score: totalScore });
}
}
- results.sort((a, b) => a.totalScore - b.totalScore);
- return results.map((r) => r.item);
+ results.sort((a, b) => a.score - b.score);
+ return results;
+}
+
+/**
+ * Filter and sort items by fuzzy match quality (best matches first).
+ * Supports space-separated tokens: all tokens must match.
+ */
+export function fuzzyFilter<T>(items: T[], query: string, getText: (item: T) => string): T[] {
+ if (!query.trim()) {
+ return items;
+ }
+ return fuzzyFilterScored(items, query, getText).map((r) => r.item);
}
diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.ts
index c013a983d0..f498791436 100644
--- a/packages/tui/src/index.ts
+++ b/packages/tui/src/index.ts
@@ -30,7 +30,7 @@ export { TruncatedText } from "./components/truncated-text.js";
// Editor component interface (for custom editors)
export type { EditorComponent } from "./editor-component.js";
// Fuzzy matching
-export { type FuzzyMatch, fuzzyFilter, fuzzyMatch } from "./fuzzy.js";
+export { type FuzzyMatch, fuzzyFilter, fuzzyFilterScored, fuzzyMatch, type ScoredItem } from "./fuzzy.js";
// Keybindings
export {
getKeybindings,
diff --git a/packages/tui/test/fuzzy.test.ts b/packages/tui/test/fuzzy.test.ts
index e784e49c08..622a260aa1 100644
--- a/packages/tui/test/fuzzy.test.ts
+++ b/packages/tui/test/fuzzy.test.ts
@@ -1,6 +1,6 @@
import assert from "node:assert";
import { describe, it } from "node:test";
-import { fuzzyFilter, fuzzyMatch } from "../src/fuzzy.js";
+import { fuzzyFilter, fuzzyFilterScored, fuzzyMatch } from "../src/fuzzy.js";
describe("fuzzyMatch", () => {
it("empty query matches everything with score 0", () => {
@@ -103,3 +103,31 @@ describe("fuzzyFilter", () => {
assert.ok(result.map((r) => r.name).includes("foobar"));
});
});
+
+describe("fuzzyFilterScored", () => {
+ it("empty query returns all items with score 0", () => {
+ const items = ["apple", "banana"];
+ const result = fuzzyFilterScored(items, "", (x: string) => x);
+ assert.deepStrictEqual(
+ result.map((r) => r.item),
+ items,
+ );
+ assert.ok(result.every((r) => r.score === 0));
+ });
+
+ it("returns scores sorted best-first", () => {
+ const items = ["a_p_p", "app"];
+ const result = fuzzyFilterScored(items, "app", (x: string) => x);
+ assert.strictEqual(result[0]?.item, "app");
+ assert.ok(result[0].score <= (result[1]?.score ?? Infinity));
+ });
+
+ it("assigns equal scores to equally-good matches, enabling a stable tie-break", () => {
+ // glm-5 / glm-5.1 / glm-5.2 all match "glm" identically; caller breaks the tie.
+ const items = ["glm-5", "glm-5.1", "glm-5.2"];
+ const result = fuzzyFilterScored(items, "glm", (x: string) => x);
+ assert.strictEqual(result.length, 3);
+ assert.strictEqual(result[0]?.score, result[1]?.score);
+ assert.strictEqual(result[1]?.score, result[2]?.score);
+ });
+});