Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/mobile/src/features/threads/ComposerCommandPopover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -198,7 +198,7 @@ const CommandRow = memo(function CommandRow(props: {
style={{ borderBottomWidth: props.isLast ? 0 : StyleSheet.hairlineWidth }}
>
{props.item.type === "path" ? (
<PierreEntryIcon path={props.item.path} kind={props.item.kind} size={16} />
<PierreEntryIcon path={props.item.path} kind={props.item.pathKind} size={16} />
) : props.item.type === "model" ? (
<ProviderIcon
iconUrl={props.item.option.providerIconUrl}
Expand Down
36 changes: 20 additions & 16 deletions apps/mobile/src/features/threads/use-composer-command-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
type ComposerEnvironmentCandidate,
matchComposerEnvironmentItems,
matchComposerThreadItems,
rankComposerMentionItems,
} from "@t3tools/client-runtime/composerThreadItems";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";

Expand Down Expand Up @@ -541,22 +542,25 @@ export function useComposerCommandMenu({
modelOptions && modelProviders
? buildComposerModelItems(modelOptions, trigger.query, modelProviders)
: [];
return [
...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,
kind: entry.kind,
label: parts[parts.length - 1] ?? entry.path,
description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
};
}),
];
return rankComposerMentionItems<ComposerCommandItem>(
[
...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 [];
Expand Down
84 changes: 44 additions & 40 deletions apps/web/src/components/chat/useComposerMenuItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import {
matchComposerEnvironmentItems,
matchComposerThreadItems,
rankComposerMentionItems,
} from "@t3tools/client-runtime/composerThreadItems";
import { useAtomValue } from "@effect/atom-react";
import { useState } from "react";
Expand Down Expand Up @@ -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<ComposerCommandItem>(
[
...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 = [
Expand Down
71 changes: 71 additions & 0 deletions packages/client-runtime/src/composerThreadItems.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
matchComposerEnvironmentItems,
matchComposerThreadItems,
rankComposerMentionItems,
type ComposerThreadCandidate,
} from "./composerThreadItems.ts";

Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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);
});
});
36 changes: 33 additions & 3 deletions packages/client-runtime/src/composerThreadItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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]) => ({
Expand All @@ -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}`,
Expand All @@ -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<T>, 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);
}
13 changes: 13 additions & 0 deletions packages/shared/src/paletteSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]!)) {
Expand Down
Loading