diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx
index bf34ff7777262..e0d1dda22aaa7 100644
--- a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx
+++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx
@@ -37,7 +37,7 @@ export type ComposerCommandItem =
readonly id: string;
readonly type: "path";
readonly path: string;
- readonly kind: "file" | "directory";
+ readonly pathKind: "file" | "directory";
readonly label: string;
readonly description: string;
}
@@ -198,7 +198,7 @@ const CommandRow = memo(function CommandRow(props: {
style={{ borderBottomWidth: props.isLast ? 0 : StyleSheet.hairlineWidth }}
>
{props.item.type === "path" ? (
-
+
) : props.item.type === "model" ? (
{
- const parts = entry.path.normalize("NFC").split("/");
- return {
- id: `path:${entry.path}`,
- type: "path" as const,
- path: entry.path,
- kind: entry.kind,
- label: parts[parts.length - 1] ?? entry.path,
- description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
- };
- }),
- ];
+ return rankComposerMentionItems(
+ [
+ ...threadItems,
+ ...environmentItems,
+ ...modelItems,
+ ...pathSearch.entries.map((entry) => {
+ const parts = entry.path.normalize("NFC").split("/");
+ return {
+ id: `path:${entry.path}`,
+ type: "path" as const,
+ path: entry.path,
+ pathKind: entry.kind,
+ label: parts[parts.length - 1] ?? entry.path,
+ description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
+ };
+ }),
+ ],
+ trigger.query,
+ );
}
return [];
diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.ts
index 295260528d7f5..a85ccb5dc4188 100644
--- a/apps/web/src/components/chat/useComposerMenuItems.ts
+++ b/apps/web/src/components/chat/useComposerMenuItems.ts
@@ -6,6 +6,7 @@ import {
import {
matchComposerEnvironmentItems,
matchComposerThreadItems,
+ rankComposerMentionItems,
} from "@t3tools/client-runtime/composerThreadItems";
import { useAtomValue } from "@effect/atom-react";
import { useState } from "react";
@@ -211,47 +212,50 @@ export function useComposerMenuItems({
const items = ((): ComposerCommandItem[] => {
if (!composerTrigger) return [];
if (composerTrigger.kind === "path") {
- return [
- ...matchComposerThreadItems(
- {
- shells: environmentThreadShells,
- environmentId,
- linkedEnvironments,
- excludeThreadId: activeThreadId,
+ return rankComposerMentionItems(
+ [
+ ...matchComposerThreadItems(
+ {
+ shells: environmentThreadShells,
+ environmentId,
+ linkedEnvironments,
+ excludeThreadId: activeThreadId,
+ query: composerTrigger.query,
+ now,
+ },
+ messages,
+ ),
+ // An answer to an agent's question carries thread links, not machines.
+ ...(questionAttachmentTarget === null && offersMachines
+ ? matchComposerEnvironmentItems(
+ {
+ environments: mentionableEnvironments,
+ linkedEnvironments,
+ environmentId,
+ query: composerTrigger.query,
+ },
+ messages,
+ )
+ : []),
+ ...matchComposerModelItems({
+ instanceEntries: modelMentions.instanceEntries,
+ modelOptionsByInstance: modelMentions.modelOptionsByInstance,
query: composerTrigger.query,
- now,
- },
- messages,
- ),
- // An answer to an agent's question carries thread links, not machines.
- ...(questionAttachmentTarget === null && offersMachines
- ? matchComposerEnvironmentItems(
- {
- environments: mentionableEnvironments,
- linkedEnvironments,
- environmentId,
- query: composerTrigger.query,
- },
- messages,
- )
- : []),
- ...matchComposerModelItems({
- instanceEntries: modelMentions.instanceEntries,
- modelOptionsByInstance: modelMentions.modelOptionsByInstance,
- query: composerTrigger.query,
- }),
- ...workspaceEntries.entries.map((entry) => ({
- id: `path:${entry.kind}:${entry.path}`,
- type: "path" as const,
- path: entry.path,
- pathKind: entry.kind,
- searchTarget: workspaceEntries.searchedTarget,
- label: basenameOfPath(entry.path).normalize("NFC"),
- description: entry.path
- .slice(0, Math.max(0, entry.path.lastIndexOf("/")))
- .normalize("NFC"),
- })),
- ];
+ }),
+ ...workspaceEntries.entries.map((entry) => ({
+ id: `path:${entry.kind}:${entry.path}`,
+ type: "path" as const,
+ path: entry.path,
+ pathKind: entry.kind,
+ searchTarget: workspaceEntries.searchedTarget,
+ label: basenameOfPath(entry.path).normalize("NFC"),
+ description: entry.path
+ .slice(0, Math.max(0, entry.path.lastIndexOf("/")))
+ .normalize("NFC"),
+ })),
+ ],
+ composerTrigger.query,
+ );
}
if (composerTrigger.kind === "slash-command") {
const builtInSlashCommandItems = [
diff --git a/packages/client-runtime/src/composerThreadItems.test.ts b/packages/client-runtime/src/composerThreadItems.test.ts
index 26ec3e7fde0cd..38543bea61c9e 100644
--- a/packages/client-runtime/src/composerThreadItems.test.ts
+++ b/packages/client-runtime/src/composerThreadItems.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
matchComposerEnvironmentItems,
matchComposerThreadItems,
+ rankComposerMentionItems,
type ComposerThreadCandidate,
} from "./composerThreadItems.ts";
@@ -113,6 +114,20 @@ describe("matchComposerEnvironmentItems", () => {
{ environmentId: EnvironmentId.make("env-mini"), label: "Mac mini", machine: "mac-mini" },
] as const;
+ it("matches a machine only from the start of a word", () => {
+ const labels = (query: string) =>
+ matchComposerEnvironmentItems({
+ environments,
+ linkedEnvironments: new Map(),
+ environmentId: EnvironmentId.make("env-here"),
+ query,
+ }).map((item) => item.label);
+ expect(labels("het")).toEqual(["Hetzner VPS"]);
+ expect(labels("mini")).toEqual(["Mac mini"]);
+ expect(labels("mac mi")).toEqual(["Mac mini"]);
+ expect(labels("ner")).toEqual([]);
+ });
+
it("offers the other machines matching the query, never the composer's own", () => {
expect(
matchComposerEnvironmentItems({
@@ -180,3 +195,59 @@ describe("matchComposerEnvironmentItems", () => {
).toEqual(["cloud"]);
});
});
+
+describe("rankComposerMentionItems", () => {
+ const thread = (label: string) => ({ type: "thread", label });
+ const machine = (label: string) => ({ type: "environment", label });
+ const file = (label: string) => ({ type: "path", label, pathKind: "file" });
+ const directory = (label: string) => ({ type: "path", label, pathKind: "directory" });
+ const model = (label: string) => ({ type: "model", label });
+
+ it.each([
+ ["dev", [directory("dev"), machine("Dev box")], ["Dev box", "dev"]],
+ [
+ "he",
+ [
+ thread("The other one"),
+ thread("He said no"),
+ machine("Hetzner VPS"),
+ file("the.json"),
+ file("Hexyz.json"),
+ file("He.json"),
+ ],
+ ["He.json", "Hetzner VPS", "He said no", "Hexyz.json", "The other one", "the.json"],
+ ],
+ [
+ "ner",
+ [thread("Partner sync"), thread("ner plan"), file("planner.md"), file("ner-notes.md")],
+ ["ner plan", "ner-notes.md", "Partner sync", "planner.md"],
+ ],
+ [
+ "sonnet",
+ [
+ thread("Sonnet pricing"),
+ model("Sonnet 5.5"),
+ model("Claude Sonnet 4"),
+ file("sonnet-notes.md"),
+ ],
+ ["Sonnet pricing", "Sonnet 5.5", "Claude Sonnet 4", "sonnet-notes.md"],
+ ],
+ [
+ "model",
+ [file("model-notes.md"), thread("FixModelPicker")],
+ ["FixModelPicker", "model-notes.md"],
+ ],
+ [
+ "resume",
+ [file("resume-notes.md"), thread("Résumé fixes")],
+ ["Résumé fixes", "resume-notes.md"],
+ ],
+ ])("orders results for %s", (query, items, expected) => {
+ expect(rankComposerMentionItems(items, query).map((item) => item.label)).toEqual(expected);
+ });
+
+ it("leaves a bare @ in the order it arrived", () => {
+ const items = [file("a.ts"), file(".env")];
+ expect(rankComposerMentionItems(items, " ")).toEqual(items);
+ });
+});
diff --git a/packages/client-runtime/src/composerThreadItems.ts b/packages/client-runtime/src/composerThreadItems.ts
index 0dd14bae76839..b099c871208cb 100644
--- a/packages/client-runtime/src/composerThreadItems.ts
+++ b/packages/client-runtime/src/composerThreadItems.ts
@@ -5,7 +5,12 @@ import {
type ScopedThreadRef,
type ThreadId,
} from "@t3tools/contracts";
-import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
+import {
+ foldSearchQuery,
+ rankSearchItems,
+ scoreThreadSearch,
+ startsSearchWord,
+} from "@t3tools/shared/paletteSearch";
import type { EnvironmentThreadShell } from "./state/models.ts";
import { threadSearchSubject, type ThreadSearchShell } from "./state/threadSearch.ts";
@@ -116,7 +121,7 @@ export function matchComposerEnvironmentItems(
},
resolve: MFunctionType = mFallback,
): ComposerEnvironmentItem[] {
- const query = input.query.trim().toLowerCase();
+ const query = foldSearchQuery(input.query);
if (query.length === 0) return [];
const paired = new Set(input.environments.map((environment) => environment.environmentId));
const linkedOnly = Array.from(input.linkedEnvironments, ([environmentId, label]) => ({
@@ -128,7 +133,7 @@ export function matchComposerEnvironmentItems(
.filter(
(environment) =>
environment.environmentId !== input.environmentId &&
- environment.label.toLowerCase().includes(query),
+ startsSearchWord(environment.label, query),
)
.map((environment) => ({
id: `environment:${environment.environmentId}`,
@@ -139,3 +144,28 @@ export function matchComposerEnvironmentItems(
description: resolve(msg("Machine", { $context: "noun, search result type" })),
}));
}
+
+/**
+ * Orders `@` results by how surely they are what was typed: a file with exactly that name, then
+ * machines, threads with a word starting with it, models (in their own order), files starting
+ * with it, and the rest.
+ */
+export function rankComposerMentionItems<
+ T extends { readonly type: string; readonly label: string; readonly pathKind?: string },
+>(items: ReadonlyArray, rawQuery: string): T[] {
+ const query = foldSearchQuery(rawQuery);
+ if (query.length === 0) return [...items];
+ const rank = ({ type, label, pathKind }: T) => {
+ if (type === "environment") return 1;
+ if (type === "model") return 2;
+ if (type === "thread") return startsSearchWord(label, query) ? 2 : 4;
+ const name = foldSearchQuery(label);
+ if (pathKind === "file" && (name === query || name.startsWith(`${query}.`))) return 0;
+ return name.startsWith(query) ? 3 : 5;
+ };
+ // Hermes lacks toSorted.
+ return items
+ .map((item) => ({ item, rank: rank(item) }))
+ .sort((left, right) => left.rank - right.rank)
+ .map(({ item }) => item);
+}
diff --git a/packages/shared/src/paletteSearch.ts b/packages/shared/src/paletteSearch.ts
index a2de064ca4969..c01f1b9e72841 100644
--- a/packages/shared/src/paletteSearch.ts
+++ b/packages/shared/src/paletteSearch.ts
@@ -142,6 +142,19 @@ export function foldSearchQuery(query: string): string {
.join(" ");
}
+/** Whether `foldedQuery`, from `foldSearchQuery`, begins a word of `text`. */
+export function startsSearchWord(text: string, foldedQuery: string): boolean {
+ const field = prepareSearchField(text);
+ for (
+ let index = field.text.indexOf(foldedQuery);
+ index !== -1;
+ index = field.text.indexOf(foldedQuery, index + 1)
+ ) {
+ if (field.wordStarts[index]) return true;
+ }
+ return false;
+}
+
function wordEnd(field: SearchField, index: number): number {
let end = index + 1;
while (end < field.text.length && !field.wordStarts[end] && ALPHANUMERIC.test(field.text[end]!)) {