@devries-cameron20 / t3code Mirror · read-only / commits / 88109cea46
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 02:00 UTC

feat(web,mobile): @-mention a model to name it for the agent (#31207)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Zack Jackson committed Nov 8, 2026 at 22:35 UTC 88109cea46dfc6735f948f165772ecbdffe8b80c
60 files changed +1645 -141
apps/mobile/assets/context-chip-icons/bot.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/bot.png differ
apps/mobile/assets/context-chip-icons/provider-claudeAgent.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-claudeAgent.png differ
apps/mobile/assets/context-chip-icons/provider-codex.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-codex.png differ
apps/mobile/assets/context-chip-icons/provider-cursor.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-cursor.png differ
apps/mobile/assets/context-chip-icons/provider-fx.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-fx.png differ
apps/mobile/assets/context-chip-icons/provider-grok.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-grok.png differ
apps/mobile/assets/context-chip-icons/provider-kiro.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-kiro.png differ
apps/mobile/assets/context-chip-icons/provider-muse.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-muse.png differ
apps/mobile/assets/context-chip-icons/provider-opencode.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-opencode.png differ
apps/mobile/assets/context-chip-icons/provider-pi.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/provider-pi.png differ
apps/mobile/scripts/sync-context-chip-icons.mjs
+90 -1
@@ -33,6 +33,7 @@ if (!skillSvg) {
33 }
34
35 const lucideIcons = [
36 + "bot",
37 "circle-dashed",
38 "film",
39 "git-merge",
@@ -84,6 +85,78 @@ for (const name of lucideIcons) {
85 }
86 await renderIcon("skill", skillSvg);
87
88 +// Provider logos, so a model chip can show what the model menu shows. Native chips take images,
89 +// not SVG. Logos that swap between black and white per theme take the text color, like the chip;
90 +// colored logos keep their colors and lend the chip their main color as its accent.
91 +const mobileProviderIcon = NodeFS.readFileSync(
92 + NodePath.join(appDirectory, "src/components/ProviderIcon.tsx"),
93 + "utf8",
94 +);
95 +function bundledPath(viewBox) {
96 + const path = mobileProviderIcon
97 + .slice(mobileProviderIcon.indexOf(`viewBox="${viewBox}"`))
98 + .match(/\bd="([^"]+)"/)?.[1];
99 + if (!path) throw new Error(`Could not read the ${viewBox} logo from ProviderIcon.tsx`);
100 + return path;
101 +}
102 +const packageClients = await Promise.all(
103 + ["cursor", "fx", "grok", "kiro", "muse", "opencode", "pi"].map(async (name) => {
104 + const module = await import(
105 + NodeURL.pathToFileURL(
106 + NodePath.join(repositoryRoot, `packages/provider-${name}/src/client.ts`),
107 + ).href
108 + );
109 + const client = Object.values(module).find((value) => value?.icon && value?.driverKind);
110 + if (!client) throw new Error(`packages/provider-${name} exports no client with an icon`);
111 + return client;
112 + }),
113 +);
114 +const providerSvg = (viewBox, paths) =>
115 + `<svg viewBox="${viewBox}" fill="none">${paths
116 + .map(
117 + (path) =>
118 + `<path d="${path.d}" fill="${path.fill}" fill-opacity="${path.opacity ?? 1}"${
119 + path.fillRule ? ` fill-rule="${path.fillRule}" clip-rule="${path.fillRule}"` : ""
120 + }/>`,
121 + )
122 + .join("")}</svg>`;
123 +const providerLogos = [
124 + {
125 + driverKind: "codex",
126 + tintsIcon: true,
127 + svg: providerSvg("100 100 411 411", [
128 + { d: bundledPath("100 100 411 411"), fill: "#ffffff", fillRule: "evenodd" },
129 + ]),
130 + },
131 + {
132 + driverKind: "claudeAgent",
133 + tintsIcon: false,
134 + accent: "#D97757",
135 + svg: providerSvg("0 0 256 257", [{ d: bundledPath("0 0 256 257"), fill: "#D97757" }]),
136 + },
137 + ...packageClients.map(({ driverKind, icon }) => {
138 + const tintsIcon = icon.fill.light !== icon.fill.dark;
139 + return {
140 + driverKind,
141 + tintsIcon,
142 + ...(tintsIcon ? {} : { accent: icon.fill.light }),
143 + svg: providerSvg(
144 + icon.viewBox,
145 + icon.paths.map((path) => ({
146 + d: path.d,
147 + fillRule: path.fillRule,
148 + fill: tintsIcon ? "#ffffff" : (path.fill ?? icon.fill).light,
149 + // A tint flattens color, so a logo's secondary shapes keep their contrast through alpha.
150 + ...(tintsIcon && path.fill ? { opacity: 0.4 } : {}),
151 + })),
152 + ),
153 + };
154 + }),
155 +];
156 +for (const { driverKind, svg } of providerLogos) {
157 + await renderIcon(`provider-${driverKind}`, svg);
158 +}
159 +
160 const tokens = [...lucideIcons, "skill"].sort();
161 const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const CONTEXT_CHIP_ICON_SOURCES = {\n${tokens
162 .map(
@@ -91,4 +164,20 @@ const generatedSource = `import type { ImageSourcePropType } from "react-native"
164 ` ${/^\w+$/.test(token) ? token : `"${token}"`}: require("../../assets/context-chip-icons/${token}.png"),`,
165 )
166 .join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;
94 -NodeFS.writeFileSync(generatedModulePath, generatedSource);
167 +const providerSource = `\nexport const PROVIDER_CHIP_ICONS: Readonly<\n Record<
168 + string,
169 + {
170 + readonly source: ImageSourcePropType;
171 + readonly tintsIcon: boolean;
172 + readonly accent?: string;
173 + }
174 + >\n> = {\n${providerLogos
175 + .toSorted((left, right) => left.driverKind.localeCompare(right.driverKind))
176 + .map(
177 + ({ driverKind, tintsIcon, accent }) =>
178 + ` ${driverKind}: {\n source: require("../../assets/context-chip-icons/provider-${driverKind}.png"),\n tintsIcon: ${tintsIcon},\n${accent ? ` accent: "${accent}",\n` : ""} },`,
179 + )
180 + .join(
181 + "\n",
182 + )}\n antigravity: {\n source: require("../../assets/antigravity.png"),\n tintsIcon: false,\n accent: "#5b87bf",\n },\n};\n`;
183 +NodeFS.writeFileSync(generatedModulePath, generatedSource + providerSource);
apps/mobile/src/components/ComposerEditor.ios.test.tsx
+1
@@ -118,6 +118,7 @@ vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode
118 vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null }));
119 vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() }));
120 vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] }));
121 +vi.mock("../state/model-mentions", () => ({ useModelMentions: () => [] }));
122 vi.mock("../state/preferences", async () => {
123 const { Atom } = await import("effect/reactivity");
124 return { mobilePreferencesAtom: Atom.make({ _tag: "Initial" }) };
apps/mobile/src/components/ComposerEditor.tsx
+9
@@ -26,6 +26,8 @@ import {
26 import { importComposerContextClipboard } from "../lib/composerContextClipboard";
27 import { startComposerDraftOperation } from "../state/composerDraftOperations";
28 import { appAtomRegistry } from "../state/atom-registry";
29 +import { enrichedModelDetails, enrichedModelReference } from "../lib/enrichedLinkPresentation";
30 +import { useModelMentions } from "../state/model-mentions";
31 import { mobilePreferencesAtom } from "../state/preferences";
32 import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread";
33 import { useLinkedEnvironments } from "../state/peerLinks";
@@ -81,6 +83,7 @@ export function ComposerEditor({
83 null,
84 );
85 const linkedEnvironments = useLinkedEnvironments(environmentId ?? null);
86 + const models = useModelMentions(environmentId ?? draft.project?.environmentId, props.value);
87 const contextImports = useAtomValue(composerContextImportsAtom);
88 const importing = draftKey ? contextImports[draftKey] === true : false;
89 const pasteContext = async (
@@ -179,6 +182,7 @@ export function ComposerEditor({
182 <NativeComposerEditor
183 key={hidden ? "hidden" : "visible"}
184 {...props}
185 + models={models}
186 enterBehavior={props.enterBehavior ?? preferredEnterBehavior}
187 onChangeText={changeText}
188 readResetGeneration={readResetGeneration}
@@ -197,6 +201,11 @@ export function ComposerEditor({
201 onOpenMention(path);
202 return;
203 }
204 + const model = enrichedModelReference(selection.source, models);
205 + if (model) {
206 + Dialog.alert(model.label, enrichedModelDetails(model));
207 + return;
208 + }
209 const document = composerDocumentAttachment(selection.source, draft.context);
210 if (document && onOpenAttachment) {
211 onOpenAttachment(document);
apps/mobile/src/features/threads/ComposerCommandPopover.tsx
+22 -3
@@ -19,6 +19,8 @@ import { AppText as Text } from "../../components/ui/AppText";
19 import { ENVIRONMENT_MACHINE_SYMBOLS } from "../../components/EnvironmentMachineSymbol";
20 import { GlassSurface } from "../../components/ui/GlassSurface";
21 import { PierreEntryIcon } from "../../components/PierreEntryIcon";
22 +import { ProviderIcon } from "../../components/ProviderIcon";
23 +import type { ModelOption } from "../../lib/modelOptions";
24 import { pullRequestStatus } from "../pull-requests/pullRequestStatus";
25 export type ComposerCommandItem =
26 | {
@@ -71,6 +73,13 @@ export type ComposerCommandItem =
73 readonly skill: ServerProviderSkill;
74 readonly label: string;
75 readonly description: string;
76 + }
77 + | {
78 + readonly id: string;
79 + readonly type: "model";
80 + readonly option: ModelOption;
81 + readonly label: string;
82 + readonly description: string;
83 };
84
85 interface ComposerCommandPopoverProps {
@@ -118,6 +127,7 @@ function itemIcon(item: ComposerCommandItem): AppSymbolName | null {
127 case "skill":
128 return SKILL_SOURCE_SYMBOL_BY_KIND[resolveProviderSkillSourceKind(item.skill)];
129 case "path":
130 + case "model":
131 return null;
132 case "thread":
133 return "text.bubble";
@@ -126,7 +136,10 @@ function itemIcon(item: ComposerCommandItem): AppSymbolName | null {
136 }
137 }
138
129 -function groupLabel(triggerKind: ComposerTriggerKind | null): string | null {
139 +function groupLabel(
140 + triggerKind: ComposerTriggerKind | null,
141 + items: ReadonlyArray<ComposerCommandItem>,
142 +): string | null {
143 switch (triggerKind) {
144 case "pull-request":
145 return "Pull requests";
@@ -135,7 +148,7 @@ function groupLabel(triggerKind: ComposerTriggerKind | null): string | null {
148 case "skill":
149 return "Skills";
150 case "path":
138 - return "Files";
151 + return items.every((item) => item.type === "path") ? "Files" : "Mentions";
152 default:
153 return null;
154 }
@@ -176,6 +189,12 @@ const CommandRow = memo(function CommandRow(props: {
189 >
190 {props.item.type === "path" ? (
191 <PierreEntryIcon path={props.item.path} kind={props.item.kind} size={16} />
192 + ) : props.item.type === "model" ? (
193 + <ProviderIcon
194 + iconUrl={props.item.option.providerIconUrl}
195 + provider={props.item.option.providerDriver}
196 + size={16}
197 + />
198 ) : iconName ? (
199 <SymbolView
200 name={iconName}
@@ -210,7 +229,7 @@ const CommandRow = memo(function CommandRow(props: {
229 export const ComposerCommandPopover = memo(function ComposerCommandPopover(
230 props: ComposerCommandPopoverProps,
231 ) {
213 - const label = groupLabel(props.triggerKind);
232 + const label = groupLabel(props.triggerKind, props.items);
233
234 return (
235 <PopoverSurface>
apps/mobile/src/features/threads/ThreadComposer.tsx
+9
@@ -538,6 +538,13 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
538 };
539
540 const mentionableEnvironments = useMentionableEnvironments();
541 + // Mentions name any model for the agent, so they aren't limited to models this thread can switch to.
542 + const mentionModelOptions = buildModelOptions(
543 + props.serverConfig,
544 + currentModelSelection,
545 + undefined,
546 + props.selectedThread.projectId,
547 + );
548 const composerMenu = useComposerCommandMenu({
549 draftMessage: draftMessage,
550 ownerKey: composerDraftKey,
@@ -559,6 +566,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
566 offersUsageLimits: usageLimitsOffered,
567 onUsageLimits:
568 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
569 + modelOptions: mentionModelOptions,
570 + modelProviders: props.serverConfig?.providers,
571 ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
572 offersSideChat: props.offersSideChat === true,
573 });
apps/mobile/src/features/threads/ThreadFeed.tsx
+8
@@ -261,6 +261,7 @@ import {
261 import { useThreadSelection } from "../../state/use-thread-selection";
262 import { useEnvironmentQuery } from "../../state/query";
263 import { serverEnvironment } from "../../state/server";
264 +import { useModelMentions } from "../../state/model-mentions";
265 import { composerDocumentAttachmentRecord } from "../../lib/composerContext";
266 import * as Option from "effect/Option";
267 import { appAtomRegistry } from "../../state/atom-registry";
@@ -1173,6 +1174,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
1174 readonly renderImage: MarkdownImageRenderer;
1175 readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
1176 }) {
1177 + const models = useModelMentions(props.environmentId, props.markdown);
1178 const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
1179 const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
1180 const linkHandlers: MarkdownLinkHandlers = {
@@ -1189,6 +1191,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
1191 onUseArtifactTemplate={props.onUseArtifactTemplate}
1192 renderImage={props.renderImage}
1193 skills={props.skills}
1194 + models={models}
1195 />
1196 );
1197 });
@@ -1201,6 +1204,7 @@ function AssistantMarkdownBlocks(props: {
1204 readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
1205 readonly renderImage: MarkdownImageRenderer;
1206 readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
1207 + readonly models: ReturnType<typeof useModelMentions>;
1208 }) {
1209 const blocks = useMemo(
1210 () =>
@@ -1240,6 +1244,7 @@ function AssistantMarkdownBlocks(props: {
1244 key={`markdown:${offset}`}
1245 markdown={renderCodexInlineDirectivesAsMarkdown(segment.markdown)}
1246 skills={props.skills}
1247 + models={props.models}
1248 textStyle={props.markdownStyles.nativeTextStyle}
1249 {...props.linkHandlers}
1250 renderImage={props.renderImage}
@@ -2469,6 +2474,7 @@ function UserMessageContent(props: UserMessageContentProps) {
2474
2475 function UserMessageMarkdownContent(props: UserMessageContentProps) {
2476 const text = props.text;
2477 + const models = useModelMentions(props.environmentId, text);
2478 const segments = parseReviewCommentMessageSegments(text);
2479 const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
2480 const contextClipboardFragment = props.context
@@ -2484,6 +2490,7 @@ function UserMessageMarkdownContent(props: UserMessageContentProps) {
2490 markdown={text}
2491 contextClipboardFragment={contextClipboardFragment}
2492 skills={props.skills}
2493 + models={models}
2494 textStyle={props.markdownStyles.nativeTextStyle}
2495 preserveSoftBreaks
2496 {...props.linkHandlers}
@@ -2516,6 +2523,7 @@ function UserMessageMarkdownContent(props: UserMessageContentProps) {
2523 markdown={text}
2524 contextClipboardFragment={contextClipboardFragment}
2525 skills={props.skills}
2526 + models={models}
2527 textStyle={props.markdownStyles.nativeTextStyle}
2528 preserveSoftBreaks
2529 {...props.linkHandlers}
apps/mobile/src/features/threads/use-composer-command-menu.test.ts
+71 -1
@@ -1,5 +1,5 @@
1 import { describe, expect, it, vi } from "vite-plus/test";
2 -import { ProviderDriverKind } from "@t3tools/contracts";
2 +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
3
4 vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
5
@@ -20,7 +20,9 @@ vi.mock("../../state/server", () => ({
20 },
21 }));
22
23 +import type { ModelOption } from "../../lib/modelOptions";
24 import {
25 + buildComposerModelItems,
26 buildComposerSlashCommandItems,
27 resolveComposerCommandSelection,
28 resolveComposerMenuSelection,
@@ -104,3 +106,71 @@ describe("mobile slash commands", () => {
106 expect(build(true, false)).toEqual([]);
107 });
108 });
109 +
110 +describe("mobile model mentions", () => {
111 + const provider = (
112 + instanceId: string,
113 + overrides: Partial<ServerProvider> = {},
114 + ): ServerProvider => ({
115 + instanceId: ProviderInstanceId.make(instanceId),
116 + driver: ProviderDriverKind.make("codex"),
117 + enabled: true,
118 + installed: true,
119 + version: null,
120 + status: "ready",
121 + auth: { status: "authenticated" },
122 + checkedAt: "2026-01-01T00:00:00.000Z",
123 + models: [],
124 + slashCommands: [],
125 + skills: [],
126 + ...overrides,
127 + });
128 + const option = (key: string, overrides: Partial<ModelOption> = {}): ModelOption => {
129 + const [instanceId = "", model = ""] = key.split(":");
130 + return {
131 + key,
132 + label: "GPT-6.1",
133 + subtitle: "",
134 + providerKey: instanceId,
135 + providerLabel: "Traex",
136 + providerDriver: "codex",
137 + isDefault: false,
138 + isLegacy: false,
139 + capabilities: null,
140 + selection: { instanceId: ProviderInstanceId.make(instanceId), model },
141 + ...overrides,
142 + };
143 + };
144 +
145 + it("offers current, visible models labelled with their provider", () => {
146 + const items = buildComposerModelItems(
147 + [
148 + option("traex:gpt-6.1"),
149 + option("opencode:traex/gpt-6.1", {
150 + subtitle: "Traex",
151 + providerLabel: "OpenCode",
152 + providerDriver: "opencode",
153 + }),
154 + option("hidden:gpt-6.1", { isHidden: true }),
155 + option("gone:gpt-6.1", { isUnavailable: true }),
156 + option("old:gpt-5", { label: "GPT-5", isLegacy: true }),
157 + ],
158 + "gpt",
159 + ["traex", "opencode", "hidden", "gone", "old"].map((id) => provider(id)),
160 + );
161 + expect(items.map((item) => [item.id, item.description]).toSorted()).toEqual([
162 + ["model:opencode:traex/gpt-6.1", "OpenCode · Traex"],
163 + ["model:traex:gpt-6.1", "Traex"],
164 + ]);
165 + });
166 +
167 + it.each([
168 + ["missing", []],
169 + ["not installed", [provider("traex", { installed: false })]],
170 + ["signed out", [provider("traex", { auth: { status: "unauthenticated" } })]],
171 + ["not ready", [provider("traex", { status: "error" })]],
172 + ["unavailable", [provider("traex", { availability: "unavailable" })]],
173 + ] as const)("does not suggest a preserved selection whose provider is %s", (_, providers) => {
174 + expect(buildComposerModelItems([option("traex:gpt-6.1")], "gpt", providers)).toEqual([]);
175 + });
176 +});
apps/mobile/src/features/threads/use-composer-command-menu.ts
+59
@@ -49,6 +49,10 @@ import {
49 resolveProviderSkillsForCwd,
50 resolveProviderSlashCommandsForCwd,
51 } from "@t3tools/client-runtime/providerSkills";
52 +import {
53 + formatComposerModelMention,
54 + rankComposerModelMentions,
55 +} from "@t3tools/client-runtime/composer-model-mentions";
56 import { useAtomRefresh } from "@effect/atom-react";
57 import { Atom } from "effect/reactivity";
58 import { useEffect, useState } from "react";
@@ -60,6 +64,7 @@ import {
64 useComposerPullRequestSearch,
65 useThreadSearch,
66 } from "../../state/queries";
67 +import type { ModelOption } from "../../lib/modelOptions";
68 import type { ComposerCommandItem } from "./ComposerCommandPopover";
69 import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
70
@@ -173,6 +178,49 @@ export function buildComposerSlashCommandItems(input: {
178 return items;
179 }
180
181 +export function buildComposerModelItems(
182 + modelOptions: ReadonlyArray<ModelOption>,
183 + query: string,
184 + providers: ReadonlyArray<ServerProvider>,
185 +): ComposerCommandItem[] {
186 + // The picker retains saved selections even when their provider is no longer usable.
187 + const readyProviderIds = new Set(
188 + providers
189 + .filter(
190 + (provider) =>
191 + provider.installed &&
192 + provider.status === "ready" &&
193 + provider.auth.status !== "unauthenticated" &&
194 + provider.availability !== "unavailable",
195 + )
196 + .map((provider) => provider.instanceId),
197 + );
198 + return rankComposerModelMentions(
199 + modelOptions.filter(
200 + (option) =>
201 + readyProviderIds.has(option.selection.instanceId) &&
202 + !option.isUnavailable &&
203 + !option.isHidden &&
204 + !option.isLegacy,
205 + ),
206 + query,
207 + (option) => ({
208 + name: option.label,
209 + ...(option.subtitle ? { subProvider: option.subtitle } : {}),
210 + driverKind: option.providerDriver,
211 + providerDisplayName: option.providerLabel,
212 + }),
213 + ).map((option) => ({
214 + id: `model:${option.key}`,
215 + type: "model",
216 + option,
217 + label: option.label,
218 + description: option.subtitle
219 + ? `${option.providerLabel} · ${option.subtitle}`
220 + : option.providerLabel,
221 + }));
222 +}
223 +
224 export function resolveComposerCommandSelection(input: {
225 readonly draftMessage: string;
226 readonly trigger: Pick<ComposerTrigger, "rangeStart" | "rangeEnd">;
@@ -188,6 +236,8 @@ export function resolveComposerCommandSelection(input: {
236 replacement = `/${item.command} `;
237 } else if (item.type === "provider-slash-command") {
238 replacement = `/${item.command.name} `;
239 + } else if (item.type === "model") {
240 + replacement = `${formatComposerModelMention(item.option.selection.instanceId, item.option.selection.model)} `;
241 }
242 return replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, replacement);
243 }
@@ -211,6 +261,8 @@ export function useComposerCommandMenu({
261 enabled = true,
262 onChangeDraftMessage,
263 onUsageLimits,
264 + modelOptions,
265 + modelProviders,
266 onFreshSession,
267 offersSideChat = false,
268 }: {
@@ -233,6 +285,8 @@ export function useComposerCommandMenu({
285 readonly enabled?: boolean;
286 readonly onChangeDraftMessage: (value: string) => void;
287 readonly onUsageLimits?: () => void;
288 + readonly modelOptions?: ReadonlyArray<ModelOption>;
289 + readonly modelProviders?: ReadonlyArray<ServerProvider>;
290 /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
291 readonly onFreshSession?: () => void;
292 readonly offersSideChat?: boolean;
@@ -462,9 +516,14 @@ export function useComposerCommandMenu({
516 const environmentItems = environmentId
517 ? matchComposerEnvironmentItems({ environments, environmentId, query: trigger.query })
518 : [];
519 + const modelItems =
520 + modelOptions && modelProviders
521 + ? buildComposerModelItems(modelOptions, trigger.query, modelProviders)
522 + : [];
523 return [
524 ...threadItems,
525 ...environmentItems,
526 + ...modelItems,
527 ...pathSearch.entries.map((entry) => {
528 const parts = entry.path.split("/");
529 return {
apps/mobile/src/lib/composerContext.test.ts
+46
@@ -12,6 +12,7 @@ import {
12 } from "@t3tools/shared/composerContextReferences";
13 import { describe, expect, it } from "vite-plus/test";
14 import {
15 + collectComposerModelTokens,
16 composerContextEditorTokens,
17 composerSkillLabels,
18 composerContextSendBlockReason,
@@ -155,6 +156,51 @@ describe("mobile composer context", () => {
156 expect(restore("deleted")?.records ?? []).toEqual([]);
157 expect(createComposerContextHistory()(source)?.records).toEqual([]);
158 });
159 + it("chips a model reference only once it is complete and names a known model", () => {
160 + const known = new Set(["model:codex/gpt-6.1"]);
161 + const modelTokens = (text: string) =>
162 + composerContextEditorTokens(
163 + text,
164 + collectComposerInlineTokens(text),
165 + new Set(),
166 + collectComposerModelTokens(text, known),
167 + )
168 + .filter((token) => token.type === "model")
169 + .map((token) => [token.source, token.start, token.end]);
170 +
171 + expect(modelTokens("Use model:codex/gpt-6.1 then stop")).toEqual([
172 + ["model:codex/gpt-6.1", 4, 23],
173 + ]);
174 + // Still being typed, so `gpt-6` cannot chip on the way to `gpt-6.1`.
175 + expect(modelTokens("Use model:codex/gpt-6.1")).toEqual([]);
176 + expect(modelTokens("Use model:openai/gpt-4o then stop")).toEqual([]);
177 + expect(modelTokens("Use `model:codex/gpt-6.1` then stop")).toEqual([]);
178 + expect(modelTokens(String.raw`\[\text{use model:codex/gpt-6.1 here}\] then stop`)).toEqual([]);
179 + const reference = formatComposerContextReference(terminal);
180 + const withContext = `${reference} model:codex/gpt-6.1 `;
181 + expect(
182 + composerContextEditorTokens(
183 + withContext,
184 + [],
185 + new Set(),
186 + collectComposerModelTokens(withContext, known),
187 + ).map((token) => token.type),
188 + ).toEqual(["context", "model"]);
189 + });
190 +
191 + it("keeps a confirmed model chip when backspace removes the space after it", () => {
192 + const known = new Set(["model:codex/gpt-6.1"]);
193 + const chip = collectComposerModelTokens("Use model:codex/gpt-6.1 ", known);
194 + expect(chip.map((token) => token.source)).toEqual(["model:codex/gpt-6.1"]);
195 +
196 + const kept = collectComposerModelTokens("Use model:codex/gpt-6.1", known, chip);
197 + expect(kept.map((token) => [token.start, token.end])).toEqual([[4, 23]]);
198 + // Still kept on the next render, until the chip itself is edited.
199 + expect(collectComposerModelTokens("Use model:codex/gpt-6.1", known, kept)).toHaveLength(1);
200 + expect(collectComposerModelTokens("Use model:codex/gpt-6.1x", known, kept)).toEqual([]);
201 + expect(collectComposerModelTokens("model:codex/gpt-6.1", known, kept)).toEqual([]);
202 + });
203 +
204 it("keeps exact source positions and repeated references alongside existing native tokens", () => {
205 const reference = formatComposerContextReference(terminal);
206 const text = `Use $babysit with $disabled $agentOnly $HOME $PATH $anything $notaskill $20 $20k and [app.ts](src/app.ts) with ${reference} then ${reference}`;
apps/mobile/src/lib/composerContext.ts
+41 -6
@@ -1,3 +1,7 @@
1 +import {
2 + collectComposerModelMentions,
3 + type ComposerModelMentionOccurrence,
4 +} from "@t3tools/client-runtime/composer-model-mentions";
5 import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
6 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7 import { filePreviewKind } from "@t3tools/shared/filePreview";
@@ -25,6 +29,7 @@ import {
29 } from "@t3tools/shared/composerContextReferences";
30 import {
31 collectComposerInlineTokens,
32 + composerMathRanges,
33 type ComposerInlineToken,
34 } from "@t3tools/shared/composerInlineTokens";
35
@@ -163,24 +168,54 @@ export function composerSkillLabels(
168 );
169 }
170
171 +/**
172 + * Like `$skill`, a typed reference waits for whitespace so `gpt-6` cannot chip on the way to
173 + * `gpt-6.1`. A chip already shown stays one when backspace removes the space after it.
174 + */
175 +export function collectComposerModelTokens(
176 + text: string,
177 + knownModels: { has(source: string): boolean },
178 + preserveTrailingFrom: ReadonlyArray<ComposerModelMentionOccurrence> = [],
179 +): ReadonlyArray<ComposerModelMentionOccurrence> {
180 + return collectComposerModelMentions(text).filter(
181 + (mention) =>
182 + knownModels.has(mention.source) &&
183 + (/\s/u.test(text[mention.end] ?? "") ||
184 + preserveTrailingFrom.some(
185 + (token) => token.start === mention.start && token.source === mention.source,
186 + )),
187 + );
188 +}
189 +
190 export function composerContextEditorTokens(
191 text: string,
192 tokens: readonly ComposerInlineToken[],
193 knownSkills: { has(name: string): boolean },
194 + modelTokens: ReadonlyArray<ComposerModelMentionOccurrence> = [],
195 ) {
196 const references = collectComposerContextReferences(text);
197 + const inlineTokens = tokens.filter(
198 + (token) =>
199 + // `$HOME` and other `$name` text that is not one of the provider's skills stays prose.
200 + (token.type !== "skill" || knownSkills.has(token.value)) &&
201 + !references.some((ref) => token.start < ref.end && token.end > ref.start),
202 + );
203 + const taken = [...inlineTokens, ...references, ...composerMathRanges(text)];
204 + const models = modelTokens.filter(
205 + (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start),
206 + );
207 return [
173 - ...tokens.filter(
174 - (token) =>
175 - // `$HOME` and other `$name` text that is not one of the provider's skills stays prose.
176 - (token.type !== "skill" || knownSkills.has(token.value)) &&
177 - !references.some((ref) => token.start < ref.end && token.end > ref.start),
178 - ),
208 + ...inlineTokens,
209 ...references.map((ref) => ({
210 type: "context" as const,
211 value: ref.label,
212 ...ref,
213 })),
214 + ...models.map((mention) => ({
215 + type: "model" as const,
216 + value: mention.model,
217 + ...mention,
218 + })),
219 ].sort((a, b) => a.start - b.start);
220 }
221
apps/mobile/src/lib/contextChipIconSource.test.ts new
+39
@@ -0,0 +1,39 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { modelChipIcon } from "./contextChipIconSource";
4 +
5 +vi.mock("./contextChipIcons.generated", () => ({
6 + CONTEXT_CHIP_ICON_SOURCES: { bot: "bot.png" },
7 + PROVIDER_CHIP_ICONS: { codex: { source: "codex.png", tintsIcon: true } },
8 +}));
9 +vi.mock("./markdownFileIcons", () => ({
10 + markdownFileIconSource: vi.fn(),
11 + markdownIconAssetUri: vi.fn(),
12 +}));
13 +
14 +describe("modelChipIcon", () => {
15 + it("prefers a provider's own image, then its logo, then a generic glyph", () => {
16 + expect(modelChipIcon({ driver: "codex", iconUrl: "https://x.test/icon.png" })).toEqual({
17 + source: { uri: "https://x.test/icon.png" },
18 + tintsIcon: false,
19 + });
20 + expect(modelChipIcon({ driver: "codex" })).toEqual({ source: "codex.png", tintsIcon: true });
21 + expect(modelChipIcon({ driver: "unknown" })).toEqual({ source: "bot.png", tintsIcon: true });
22 + });
23 +
24 + it("never hands a native chip an SVG it cannot decode", () => {
25 + for (const iconUrl of [
26 + "https://cdn.agentclientprotocol.com/registry/v1/latest/devin.svg",
27 + "https://x.test/icon.SVG?v=2",
28 + ]) {
29 + expect(modelChipIcon({ driver: "acpRegistry", iconUrl })).toEqual({
30 + source: "bot.png",
31 + tintsIcon: true,
32 + });
33 + }
34 + expect(modelChipIcon({ driver: "codex", iconUrl: "https://x.test/icon.svg" })).toEqual({
35 + source: "codex.png",
36 + tintsIcon: true,
37 + });
38 + });
39 +});
apps/mobile/src/lib/contextChipIconSource.ts
+20 -1
@@ -1,5 +1,5 @@
1 import type { ContextChipIconRef } from "./composerChipPresentation";
2 -import { CONTEXT_CHIP_ICON_SOURCES } from "./contextChipIcons.generated";
2 +import { CONTEXT_CHIP_ICON_SOURCES, PROVIDER_CHIP_ICONS } from "./contextChipIcons.generated";
3 import { markdownFileIconSource, markdownIconAssetUri } from "./markdownFileIcons";
4
5 export function contextChipIconSource(icon: ContextChipIconRef) {
@@ -11,3 +11,22 @@ export function contextChipIconSource(icon: ContextChipIconRef) {
11 export function contextChipIconUri(icon: ContextChipIconRef): string | null {
12 return markdownIconAssetUri(contextChipIconSource(icon)) ?? null;
13 }
14 +
15 +// ACP registry icons are SVG, which native chips cannot decode.
16 +const isRasterIconUrl = (url: string | undefined): url is string =>
17 + url !== undefined && url !== "" && !/\.svg(?:$|[?#])/iu.test(url);
18 +
19 +/** A provider's own raster image, else its bundled logo, else a generic glyph; colored logos carry an accent. */
20 +export function modelChipIcon(model: {
21 + readonly driver: string;
22 + readonly iconUrl?: string | undefined;
23 +}): (typeof PROVIDER_CHIP_ICONS)[string] {
24 + if (isRasterIconUrl(model.iconUrl)) return { source: { uri: model.iconUrl }, tintsIcon: false };
25 + return (
26 + PROVIDER_CHIP_ICONS[model.driver] ?? { source: CONTEXT_CHIP_ICON_SOURCES.bot, tintsIcon: true }
27 + );
28 +}
29 +
30 +export function modelChipIconUri(model: Parameters<typeof modelChipIcon>[0]): string | null {
31 + return markdownIconAssetUri(modelChipIcon(model).source) ?? null;
32 +}
apps/mobile/src/lib/contextChipIcons.generated.ts
+57
@@ -1,6 +1,7 @@
1 import type { ImageSourcePropType } from "react-native";
2
3 export const CONTEXT_CHIP_ICON_SOURCES = {
4 + bot: require("../../assets/context-chip-icons/bot.png"),
5 "circle-dashed": require("../../assets/context-chip-icons/circle-dashed.png"),
6 film: require("../../assets/context-chip-icons/film.png"),
7 "git-merge": require("../../assets/context-chip-icons/git-merge.png"),
@@ -15,3 +16,59 @@ export const CONTEXT_CHIP_ICON_SOURCES = {
16 skill: require("../../assets/context-chip-icons/skill.png"),
17 terminal: require("../../assets/context-chip-icons/terminal.png"),
18 } as const satisfies Readonly<Record<string, ImageSourcePropType>>;
19 +
20 +export const PROVIDER_CHIP_ICONS: Readonly<
21 + Record<
22 + string,
23 + {
24 + readonly source: ImageSourcePropType;
25 + readonly tintsIcon: boolean;
26 + readonly accent?: string;
27 + }
28 + >
29 +> = {
30 + claudeAgent: {
31 + source: require("../../assets/context-chip-icons/provider-claudeAgent.png"),
32 + tintsIcon: false,
33 + accent: "#D97757",
34 + },
35 + codex: {
36 + source: require("../../assets/context-chip-icons/provider-codex.png"),
37 + tintsIcon: true,
38 + },
39 + cursor: {
40 + source: require("../../assets/context-chip-icons/provider-cursor.png"),
41 + tintsIcon: true,
42 + },
43 + fx: {
44 + source: require("../../assets/context-chip-icons/provider-fx.png"),
45 + tintsIcon: true,
46 + },
47 + grok: {
48 + source: require("../../assets/context-chip-icons/provider-grok.png"),
49 + tintsIcon: true,
50 + },
51 + kiro: {
52 + source: require("../../assets/context-chip-icons/provider-kiro.png"),
53 + tintsIcon: false,
54 + accent: "#9046FF",
55 + },
56 + muse: {
57 + source: require("../../assets/context-chip-icons/provider-muse.png"),
58 + tintsIcon: false,
59 + accent: "#0081fb",
60 + },
61 + opencode: {
62 + source: require("../../assets/context-chip-icons/provider-opencode.png"),
63 + tintsIcon: true,
64 + },
65 + pi: {
66 + source: require("../../assets/context-chip-icons/provider-pi.png"),
67 + tintsIcon: true,
68 + },
69 + antigravity: {
70 + source: require("../../assets/antigravity.png"),
71 + tintsIcon: false,
72 + accent: "#5b87bf",
73 + },
74 +};
apps/mobile/src/lib/enrichedLinkPresentation.test.ts
+47
@@ -2,6 +2,10 @@ import { describe, expect, it } from "vite-plus/test";
2 import type { ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts";
3 import {
4 enrichedLinkVariantPattern,
5 + buildEnrichedModelReferences,
6 + enrichedModelLinkRegex,
7 + enrichedModelReference,
8 + enrichedTextLinkRegex,
9 enrichedSkillLinkRegex,
10 enrichedThreadLinkPresentation,
11 ENRICHED_INLINE_FILE_LINK_REGEX,
@@ -42,6 +46,49 @@ describe("Enriched link presentation", () => {
46 expect(enrichedSkillLinkRegex([])).toBeNull();
47 });
48
49 + it("recognizes only complete known models in prose and resolves their display names", () => {
50 + const models = buildEnrichedModelReferences([
51 + {
52 + instanceId: "codex",
53 + driver: "codex",
54 + models: [
55 + { slug: "gpt-6.1", name: "OpenAI GPT-6.1", subProvider: "OpenAI" },
56 + { slug: "gpt-6.1-sol[1m]", name: "GPT-6.1 Sol" },
57 + ],
58 + },
59 + ]);
60 + const regex = enrichedModelLinkRegex(models);
61 + for (const text of [
62 + "Try model:codex/gpt-6.1 next",
63 + "Try (model:codex/gpt-6.1).",
64 + "Try [model:codex/gpt-6.1] next",
65 + '"model:codex/gpt-6.1"',
66 + ]) {
67 + const source = regex?.exec(text)?.[0];
68 + expect(source, text).toBe("model:codex/gpt-6.1");
69 + expect(enrichedModelReference(source!, models)?.label).toBe("GPT-6.1");
70 + }
71 + expect(regex?.exec("Try model:codex/gpt-6.1-sol[1m].")?.[0]).toBe(
72 + "model:codex/gpt-6.1-sol[1m]",
73 + );
74 + for (const text of [
75 + "model:openai/gpt-4o",
76 + "model:codex/gpt-6.1-extra",
77 + "model:codex/gpt-6.1.2",
78 + "model:codex/gpt-6X1",
79 + "premodel:codex/gpt-6.1",
80 + ]) {
81 + expect(regex?.exec(text), text).toBeNull();
82 + }
83 + expect(enrichedModelReference("model:openai/gpt-4o", models)).toBeUndefined();
84 + expect(enrichedModelLinkRegex([])).toBeNull();
85 + expect(enrichedTextLinkRegex([], [])).toBeNull();
86 + const combined = enrichedTextLinkRegex([{ name: "review" }], models);
87 + expect(
88 + "Use $review with (model:codex/gpt-6.1).".match(new RegExp(combined!.source, "gu")),
89 + ).toEqual(["$review", "model:codex/gpt-6.1"]);
90 + });
91 +
92 it("matches only the complete URL, including literal regex metacharacters", () => {
93 const url = "file:///workspace/app[1].tsx?line=3+4";
94 const pattern = new RegExp(enrichedLinkVariantPattern(url));
apps/mobile/src/lib/enrichedLinkPresentation.ts
+82 -1
@@ -7,7 +7,11 @@ import {
7 type ContextChipIconRef,
8 UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,
9 } from "./composerChipPresentation";
10 -import type { SelectableMarkdownSkill } from "../native/SelectableMarkdownText.types";
10 +import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions";
11 +import type {
12 + SelectableMarkdownModel,
13 + SelectableMarkdownSkill,
14 +} from "../native/SelectableMarkdownText.types";
15 import {
16 formatComposerContextHref,
17 parseComposerContextHref,
@@ -123,3 +127,80 @@ export function enrichedSkillReference(
127 export function enrichedSkillInstructionsPath(skill: SelectableMarkdownSkill) {
128 return skill.path && !/^[a-z][a-z\d+.-]*:\/\//i.test(skill.path) ? skill.path : undefined;
129 }
130 +
131 +export function buildEnrichedModelReferences(
132 + providers: ReadonlyArray<{
133 + readonly instanceId: string;
134 + readonly driver: string;
135 + readonly displayName?: string | undefined;
136 + readonly iconUrl?: string | undefined;
137 + readonly models: ReadonlyArray<{
138 + readonly slug: string;
139 + readonly name: string;
140 + readonly subProvider?: string | undefined;
141 + }>;
142 + }>,
143 + sources?: ReadonlySet<string>,
144 +): ReadonlyArray<SelectableMarkdownModel> {
145 + return providers.flatMap((provider) =>
146 + provider.models
147 + .filter(
148 + (model) =>
149 + !sources || sources.has(formatComposerModelMention(provider.instanceId, model.slug)),
150 + )
151 + .map((model) => {
152 + const qualifier = model.subProvider?.trim();
153 + const label = qualifier
154 + ? model.name
155 + .replace(
156 + new RegExp(
157 + `^${qualifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*[.:/-]\\s*|\\s+)`,
158 + "iu",
159 + ),
160 + "",
161 + )
162 + .trim() || model.name
163 + : model.name;
164 + return {
165 + source: formatComposerModelMention(provider.instanceId, model.slug),
166 + label,
167 + providerLabel: qualifier || provider.displayName || provider.instanceId,
168 + driver: provider.driver,
169 + iconUrl: provider.iconUrl,
170 + };
171 + }),
172 + );
173 +}
174 +
175 +export function enrichedModelLinkRegex(models?: ReadonlyArray<SelectableMarkdownModel>) {
176 + if (!models?.length) return null;
177 + const alternatives = models
178 + .map((model) => model.source)
179 + .sort((a, b) => b.length - a.length)
180 + .map((source) => source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
181 + return new RegExp(
182 + `(?<![^\\s,(\\["'])(?:${alternatives.join("|")})(?=$|[\\s,"']|[.;:!?\\)\\]]+(?=$|[\\s,"']))`,
183 + "u",
184 + );
185 +}
186 +
187 +export function enrichedModelReference(
188 + source: string,
189 + models?: ReadonlyArray<SelectableMarkdownModel>,
190 +) {
191 + return models?.find((model) => model.source === source);
192 +}
193 +
194 +export function enrichedModelDetails(model: SelectableMarkdownModel) {
195 + return `${model.providerLabel}\n${model.source}`;
196 +}
197 +
198 +export function enrichedTextLinkRegex(
199 + skills?: ReadonlyArray<SelectableMarkdownSkill>,
200 + models?: ReadonlyArray<SelectableMarkdownModel>,
201 +) {
202 + const patterns = [enrichedSkillLinkRegex(skills), enrichedModelLinkRegex(models)]
203 + .filter((pattern) => pattern !== null)
204 + .map((pattern) => `(?:${pattern.source})`);
205 + return patterns.length ? new RegExp(patterns.join("|"), "u") : null;
206 +}
apps/mobile/src/native/EnrichedMarkdownText.tsx
+52 -26
@@ -27,10 +27,13 @@ import { useAppearancePreferences } from "../features/settings/appearance/Appear
27 import { Menu } from "../components/ui/Menu";
28 import { useEnrichedLinkVariants } from "./useEnrichedLinkVariants";
29 import { useRetryingImageSource } from "./useRetryingImageSource";
30 +import * as Dialog from "../components/ui/Dialog";
31 import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
32 import {
33 ENRICHED_INLINE_FILE_LINK_REGEX,
33 - enrichedSkillLinkRegex,
34 + enrichedTextLinkRegex,
35 + enrichedModelDetails,
36 + enrichedModelReference,
37 enrichedLinkVariantPattern,
38 } from "../lib/enrichedLinkPresentation";
39
@@ -218,28 +221,49 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
221 : urls,
222 );
223 };
221 - const skillRegex = useMemo(() => enrichedSkillLinkRegex(props.skills), [props.skills]);
222 - // Skill links come from linkRecognition, which runs as the text is drawn, so
224 + const textLinkRegex = useMemo(
225 + () => enrichedTextLinkRegex(props.skills, props.models),
226 + [props.skills, props.models],
227 + );
228 + // Recognized text links are added as the text is drawn, so
229 // onLinksChange never reports them. Joined so a streaming tick keeps the value.
224 - const skillLinkKey = useMemo(
230 + const textLinkKey = useMemo(
231 () =>
226 - skillRegex
227 - ? [...new Set(markdown.match(new RegExp(skillRegex.source, "gu")) ?? [])].join("\n")
232 + textLinkRegex
233 + ? [...new Set(markdown.match(new RegExp(textLinkRegex.source, "gu")) ?? [])].join("\n")
234 : "",
229 - [markdown, skillRegex],
235 + [markdown, textLinkRegex],
236 );
231 - const linkUrls = skillLinkKey
232 - ? [...new Set([...parsedLinkUrls, ...skillLinkKey.split("\n")])]
237 + const linkUrls = textLinkKey
238 + ? [...new Set([...parsedLinkUrls, ...textLinkKey.split("\n")])]
239 : parsedLinkUrls;
240 const { linkVariants, linkPillContent } = useEnrichedLinkVariants(linkUrls, props, fileHrefs);
235 - const linkRecognition = useMemo(() => ({ text: skillRegex ?? undefined }), [skillRegex]);
241 + const linkRecognition = useMemo(() => ({ text: textLinkRegex ?? undefined }), [textLinkRegex]);
242 const [activeMenu, setActiveMenu] = useState<{
243 url: string;
244 menu: NonNullable<ReturnType<NonNullable<typeof props.fileContextMenu>>>;
245 } | null>(null);
246 const { fileContextMenu, onFileContextMenuAction } = props;
241 - const onLinkPress = (url: string) =>
247 + const onLinkPress = (url: string) => {
248 + const model = enrichedModelReference(url, props.models);
249 + if (model) {
250 + Dialog.alert(model.label, enrichedModelDetails(model));
251 + return;
252 + }
253 (fileHrefs.has(url) ? (props.onImagePress ?? props.onLinkPress) : props.onLinkPress)?.(url);
254 + };
255 + const modelContextMenu = (url: string) => {
256 + const model = enrichedModelReference(url, props.models);
257 + return model
258 + ? {
259 + title: model.label,
260 + actions: [
261 + { id: "enriched-copy-link", title: "Copy model reference" },
262 + { id: "enriched-share-link", title: "Share model reference" },
263 + ],
264 + }
265 + : undefined;
266 + };
267 const performMenuAction = (url: string, actionId: string) => {
268 if (actionId === "enriched-open-link") onLinkPress(url);
269 else if (actionId === "enriched-copy-link") copyTextWithHaptic(url);
@@ -250,14 +274,15 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
274 Platform.OS === "ios" && (fileContextMenu || props.onLinkPress || props.onImagePress)
275 ? Object.fromEntries(
276 linkUrls.map((url) => {
253 - const menu = fileContextMenu?.(url) ?? {
254 - title: url,
255 - actions: [
256 - { id: "enriched-open-link", title: "Open link" },
257 - { id: "enriched-copy-link", title: "Copy link" },
258 - { id: "enriched-share-link", title: "Share link" },
259 - ],
260 - };
277 + const menu = modelContextMenu(url) ??
278 + fileContextMenu?.(url) ?? {
279 + title: url,
280 + actions: [
281 + { id: "enriched-open-link", title: "Open link" },
282 + { id: "enriched-copy-link", title: "Copy link" },
283 + { id: "enriched-share-link", title: "Share link" },
284 + ],
285 + };
286 return [
287 enrichedLinkVariantPattern(url),
288 menu.actions.map((action) => ({
@@ -329,13 +354,14 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
354 const onLinkLongPress =
355 Platform.OS === "android" && props.fileContextMenu
356 ? ({ url }: { url: string }) => {
332 - const menu = props.fileContextMenu?.(url) ?? {
333 - title: url,
334 - actions: [
335 - { id: "enriched-open-link", title: "Open link" },
336 - { id: "enriched-copy-link", title: "Copy link" },
337 - ],
338 - };
357 + const menu = modelContextMenu(url) ??
358 + props.fileContextMenu?.(url) ?? {
359 + title: url,
360 + actions: [
361 + { id: "enriched-open-link", title: "Open link" },
362 + { id: "enriched-copy-link", title: "Copy link" },
363 + ],
364 + };
365 setActiveMenu({ url, menu });
366 openAndroidMenu?.();
367 }
apps/mobile/src/native/SelectableMarkdownText.types.ts
+9
@@ -27,6 +27,14 @@ export interface SelectableMarkdownSkill {
27 readonly path?: string;
28 }
29
30 +export interface SelectableMarkdownModel {
31 + readonly source: string;
32 + readonly label: string;
33 + readonly providerLabel: string;
34 + readonly driver: string;
35 + readonly iconUrl?: string | undefined;
36 +}
37 +
38 export interface MarkdownImageRequest {
39 readonly href: string;
40 readonly alt: string | null;
@@ -66,6 +74,7 @@ export interface SelectableMarkdownTextProps {
74 readonly markdown: string;
75 readonly textStyle: NativeMarkdownTextStyle;
76 readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
77 + readonly models?: ReadonlyArray<SelectableMarkdownModel>;
78 readonly preserveSoftBreaks?: boolean;
79 readonly onLinkPress?: (href: string) => void;
80 readonly fileContextMenu?: (href: string) => MarkdownFileContextMenu | undefined;
apps/mobile/src/native/T3ComposerEditor.ios.tsx
+29 -9
@@ -2,6 +2,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/
2 import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
3 import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4 import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
5 +import { useComposerModelTokens } from "./useComposerModelTokens";
6 import { requireNativeView } from "expo";
7 import {
8 useCallback,
@@ -22,7 +23,7 @@ import {
23 contextChipPresentation,
24 contextRecordFileName,
25 } from "../lib/composerChipPresentation";
25 -import { contextChipIconUri } from "../lib/contextChipIconSource";
26 +import { contextChipIconUri, modelChipIcon, modelChipIconUri } from "../lib/contextChipIconSource";
27 import { useUniwindTheme } from "../lib/useUniwindTheme";
28 import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
29 import { FONT_FAMILIES } from "../lib/fontFamilies";
@@ -40,6 +41,7 @@ import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerE
41
42 const NATIVE_MODULE_NAME = "T3ComposerEditor";
43 const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
44 +const EMPTY_MODELS: NonNullable<ComposerEditorProps["models"]> = [];
45 const NO_RESET = () => 0;
46
47 type NativeEditorEvent = NativeSyntheticEvent<{
@@ -137,6 +139,7 @@ function basename(path: string): string {
139 export function ComposerEditor({
140 ref,
141 skills = EMPTY_SKILLS,
142 + models = EMPTY_MODELS,
143 selection,
144 style,
145 textStyle,
@@ -178,10 +181,12 @@ export function ComposerEditor({
181 const fontFamily = FONT_FAMILIES.regular;
182
183 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
184 + const { modelsBySource, modelTokens } = useComposerModelTokens(props.value, models);
185 const chipTextColor = createNativeComposerTheme(theme).text;
186 const tokensJson = useMemo(() => {
187 return JSON.stringify(
184 - composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
188 + composerContextEditorTokens(props.value, tokens, skillLabels, modelTokens).map((token) => {
189 + const model = token.type === "model" ? modelsBySource.get(token.source) : undefined;
190 const record =
191 token.type === "context"
192 ? props.context?.records.find((record) => record.contextId === token.contextId)
@@ -199,20 +204,35 @@ export function ComposerEditor({
204 source: token.source,
205 start: token.start,
206 end: token.end,
202 - accent: contextChipAccent(presentation.accent, theme, chipTextColor),
207 + accent: contextChipAccent(
208 + model ? modelChipIcon(model).accent : presentation.accent,
209 + theme,
210 + chipTextColor,
211 + ),
212 label:
213 token.type === "skill"
214 ? (skillLabels.get(token.value) ?? token.value)
206 - : token.type === "context"
207 - ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
208 - : basename(token.value),
215 + : model
216 + ? model.label
217 + : token.type === "context"
218 + ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
219 + : basename(token.value),
220 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
210 - iconUri: contextChipIconUri(icon),
211 - tintsIcon: icon.kind === "chip",
221 + iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon),
222 + tintsIcon: model ? modelChipIcon(model).tintsIcon : icon.kind === "chip",
223 };
224 }),
225 );
215 - }, [props.value, tokens, props.context, skillLabels, theme, chipTextColor]);
226 + }, [
227 + props.value,
228 + tokens,
229 + props.context,
230 + skillLabels,
231 + modelsBySource,
232 + modelTokens,
233 + theme,
234 + chipTextColor,
235 + ]);
236 // Every render resolves against the snapshot history, so a render whose
237 // (value, selection) lags the acknowledged native state is stamped behind
238 // the native revision and rejected by the editor instead of re-applying a
apps/mobile/src/native/T3ComposerEditor.native.tsx
+31 -10
@@ -2,6 +2,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/
2 import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
3 import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4 import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
5 +import { useComposerModelTokens } from "./useComposerModelTokens";
6 import { requireNativeView } from "expo";
7 import { TextInputWrapper } from "expo-paste-input";
8 import {
@@ -23,7 +24,7 @@ import {
24 contextChipPresentation,
25 contextRecordFileName,
26 } from "../lib/composerChipPresentation";
26 -import { contextChipIconUri } from "../lib/contextChipIconSource";
27 +import { contextChipIconUri, modelChipIcon, modelChipIconUri } from "../lib/contextChipIconSource";
28 import { MOBILE_TYPOGRAPHY } from "../lib/typography";
29 import { useNativePaste } from "../lib/useNativePaste";
30 import { FONT_FAMILIES } from "../lib/fontFamilies";
@@ -42,6 +43,7 @@ import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerE
43
44 const NATIVE_MODULE_NAME = "T3ComposerEditor";
45 const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
46 +const EMPTY_MODELS: NonNullable<ComposerEditorProps["models"]> = [];
47
48 type NativeEditorEvent = NativeSyntheticEvent<{
49 readonly value: string;
@@ -125,6 +127,7 @@ function basename(path: string): string {
127 export function ComposerEditor({
128 ref,
129 skills = EMPTY_SKILLS,
130 + models = EMPTY_MODELS,
131 selection,
132 style,
133 textStyle,
@@ -173,10 +176,12 @@ export function ComposerEditor({
176 );
177
178 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
179 + const { modelsBySource, modelTokens } = useComposerModelTokens(props.value, models);
180 const chipTextColor = createNativeComposerTheme(theme).text;
181 const tokensJson = useMemo(() => {
182 return JSON.stringify(
179 - composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
183 + composerContextEditorTokens(props.value, tokens, skillLabels, modelTokens).map((token) => {
184 + const model = token.type === "model" ? modelsBySource.get(token.source) : undefined;
185 const record =
186 token.type === "context"
187 ? props.context?.records.find((record) => record.contextId === token.contextId)
@@ -190,24 +195,40 @@ export function ComposerEditor({
195 token.type === "mention" ? token.value : contextRecordFileName(record),
196 );
197 return {
193 - type: token.type,
198 + // Android taps only known token types; a model chip opens like a skill chip.
199 + type: token.type === "model" ? "skill" : token.type,
200 source: token.source,
201 start: token.start,
202 end: token.end,
197 - accent: contextChipAccent(presentation.accent, theme, chipTextColor),
203 + accent: contextChipAccent(
204 + model ? modelChipIcon(model).accent : presentation.accent,
205 + theme,
206 + chipTextColor,
207 + ),
208 label:
209 token.type === "skill"
210 ? (skillLabels.get(token.value) ?? token.value)
201 - : token.type === "context"
202 - ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
203 - : basename(token.value),
211 + : model
212 + ? model.label
213 + : token.type === "context"
214 + ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
215 + : basename(token.value),
216 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
205 - iconUri: contextChipIconUri(icon),
206 - tintsIcon: icon.kind === "chip",
217 + iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon),
218 + tintsIcon: model ? modelChipIcon(model).tintsIcon : icon.kind === "chip",
219 };
220 }),
221 );
210 - }, [props.value, tokens, props.context, skillLabels, theme, chipTextColor]);
222 + }, [
223 + props.value,
224 + tokens,
225 + props.context,
226 + skillLabels,
227 + modelsBySource,
228 + modelTokens,
229 + theme,
230 + chipTextColor,
231 + ]);
232 // Every render resolves against the snapshot history, so a render whose
233 // (value, selection) lags the acknowledged native state is stamped behind
234 // the native revision and rejected by the editor instead of re-applying a
apps/mobile/src/native/T3ComposerEditor.types.ts
+2
@@ -1,3 +1,4 @@
1 +import type { SelectableMarkdownModel } from "./SelectableMarkdownText.types";
2 import type { OrchestrationMessageContext, ServerProviderSkill } from "@t3tools/contracts";
3 import type { Ref } from "react";
4 import type { StyleProp, TextStyle, ViewStyle } from "react-native";
@@ -44,6 +45,7 @@ export interface ComposerEditorProps {
45 > &
46 Partial<Pick<ServerProviderSkill, "path">>
47 >;
48 + readonly models?: ReadonlyArray<SelectableMarkdownModel>;
49 readonly selection?: ComposerEditorSelection;
50 readonly placeholder?: string;
51 readonly autoFocus?: boolean;
apps/mobile/src/native/useComposerModelTokens.ts new
+26
@@ -0,0 +1,26 @@
1 +import { useMemo, useState } from "react";
2 +
3 +import { collectComposerModelTokens } from "../lib/composerContext";
4 +import type { SelectableMarkdownModel } from "./SelectableMarkdownText.types";
5 +
6 +/** Render-phase state, like the editors' inline tokens, so an abandoned render leaves no chip behind. */
7 +export function useComposerModelTokens(
8 + value: string,
9 + models: ReadonlyArray<SelectableMarkdownModel>,
10 +) {
11 + const modelsBySource = useMemo(
12 + () => new Map(models.map((model) => [model.source, model])),
13 + [models],
14 + );
15 + const [confirmed, setConfirmed] = useState(() => ({
16 + value,
17 + modelsBySource,
18 + tokens: collectComposerModelTokens(value, modelsBySource),
19 + }));
20 + let tokens = confirmed.tokens;
21 + if (confirmed.value !== value || confirmed.modelsBySource !== modelsBySource) {
22 + tokens = collectComposerModelTokens(value, modelsBySource, confirmed.tokens);
23 + setConfirmed({ value, modelsBySource, tokens });
24 + }
25 + return { modelsBySource, modelTokens: tokens };
26 +}
apps/mobile/src/native/useEnrichedLinkVariants.ts
+18 -4
@@ -1,3 +1,4 @@
1 +import { modelChipIcon } from "../lib/contextChipIconSource";
2 import { useMemo } from "react";
3 import { Image } from "react-native";
4 import type { LinkPillContent, MarkdownStyle } from "react-native-enriched-markdown";
@@ -17,6 +18,7 @@ import type {
18 import {
19 enrichedContextLinkPresentation,
20 enrichedLinkVariantPattern,
21 + enrichedModelReference,
22 enrichedSkillDisplayName,
23 enrichedSkillReference,
24 enrichedThreadLinkPresentation,
@@ -59,7 +61,7 @@ export function withChipIcon(
61
62 function presentation(
63 url: string,
62 - props: Pick<SelectableMarkdownTextProps, "linkCustomization" | "skills" | "textStyle">,
64 + props: Pick<SelectableMarkdownTextProps, "linkCustomization" | "skills" | "models" | "textStyle">,
65 ): MarkdownLinkCustomization | undefined {
66 const custom = props.linkCustomization?.(url);
67 if (custom) return custom;
@@ -72,6 +74,18 @@ function presentation(
74 icon: CONTEXT_CHIP_ICON_SOURCES.skill,
75 chip: { accent: contextChipPresentation("skill").accent, tintsIcon: true },
76 };
77 + const model = enrichedModelReference(url, props.models);
78 + if (model) {
79 + const icon = modelChipIcon(model);
80 + return {
81 + label: model.label,
82 + icon: icon.source,
83 + chip: {
84 + accent: icon.accent,
85 + tintsIcon: icon.tintsIcon,
86 + },
87 + };
88 + }
89 const link = resolveMarkdownLinkPresentation(url);
90 if (link.kind === "file")
91 return {
@@ -94,7 +108,7 @@ export function useEnrichedLinkVariants(
108 props: SelectableMarkdownTextProps,
109 fileHrefs: ReadonlySet<string>,
110 ) {
97 - const { linkCustomization, skills, textStyle, fileEmbedLabel } = props;
111 + const { linkCustomization, skills, models, textStyle, fileEmbedLabel } = props;
112 const theme = useUniwindTheme();
113 const links = useMemo(() => {
114 const byUrl = new Map<string, MarkdownLinkCustomization>();
@@ -107,11 +121,11 @@ export function useEnrichedLinkVariants(
121 color: textStyle.fileTextColor,
122 icon: markdownFileIconSource(resolveMarkdownFileIcon(label)),
123 }
110 - : presentation(url, { linkCustomization, skills, textStyle });
124 + : presentation(url, { linkCustomization, skills, models, textStyle });
125 if (value) byUrl.set(url, value);
126 }
127 return byUrl;
114 - }, [urls, linkCustomization, skills, textStyle, fileHrefs, fileEmbedLabel]);
128 + }, [urls, linkCustomization, skills, models, textStyle, fileHrefs, fileEmbedLabel]);
129 const chipForegrounds = useMemo(
130 () =>
131 new Map(
apps/mobile/src/state/model-mentions.ts new
+48
@@ -0,0 +1,48 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions";
3 +import type { EnvironmentId } from "@t3tools/contracts";
4 +import * as Option from "effect/Option";
5 +import { Atom } from "effect/reactivity";
6 +
7 +import { buildEnrichedModelReferences } from "../lib/enrichedLinkPresentation";
8 +import type { SelectableMarkdownModel } from "../native/SelectableMarkdownText.types";
9 +import { serverEnvironment } from "./server";
10 +
11 +const EMPTY_MODELS: ReadonlyArray<SelectableMarkdownModel> = [];
12 +const emptyModelsAtom = Atom.make(EMPTY_MODELS);
13 +
14 +const modelMentionsAtom = Atom.family((key: string) => {
15 + const [environmentId, ...sources] = key.split("\n");
16 + const wanted = new Set(sources);
17 + return Atom.make((get) => {
18 + const models = buildEnrichedModelReferences(
19 + get(serverEnvironment.providersValueAtom(environmentId as EnvironmentId)) ?? [],
20 + wanted,
21 + );
22 + const previous = Option.getOrUndefined(get.self<ReadonlyArray<SelectableMarkdownModel>>());
23 + // Provider status pushes do not change a message's chip labels or artwork.
24 + return previous?.length === models.length &&
25 + previous.every((model, index) => {
26 + const next = models[index]!;
27 + return (
28 + model.source === next.source &&
29 + model.label === next.label &&
30 + model.providerLabel === next.providerLabel &&
31 + model.iconUrl === next.iconUrl
32 + );
33 + })
34 + ? previous
35 + : models;
36 + }).pipe(Atom.withLabel("mobile:model-mentions"));
37 +});
38 +
39 +export function useModelMentions(environmentId: EnvironmentId | undefined, markdown: string) {
40 + const sources = [
41 + ...new Set(collectComposerModelMentions(markdown).map((mention) => mention.source)),
42 + ].sort();
43 + return useAtomValue(
44 + environmentId && sources.length
45 + ? modelMentionsAtom([environmentId, ...sources].join("\n"))
46 + : emptyModelsAtom,
47 + );
48 +}
apps/web/src/components/ChatMarkdown.browser.test.tsx
+30 -1
@@ -39,9 +39,25 @@ vi.mock(import("../state/server"), async (original) => {
39 const actual = await original();
40 const { Atom } = await import("effect/reactivity");
41 const noConfig = Atom.make(null);
42 + const modelsConfig = Atom.make({
43 + availableEditors: [],
44 + settings: { providerInstances: {} },
45 + providers: [
46 + {
47 + instanceId: "codex",
48 + driver: "codex",
49 + displayName: "Codex",
50 + models: [{ slug: "gpt-6.1", name: "GPT-6.1", isCustom: false, capabilities: {} }],
51 + },
52 + ],
53 + });
54 return {
55 ...actual,
44 - serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
56 + serverEnvironment: {
57 + ...actual.serverEnvironment,
58 + configValueAtom: ((environmentId: string) =>
59 + environmentId === "models" ? modelsConfig : noConfig) as never,
60 + },
61 };
62 });
63 vi.mock(import("../state/session"), async (original) => {
@@ -415,6 +431,19 @@ describe("ChatMarkdown skill chips", () => {
431
432 expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md");
433 });
434 +
435 + it("names a mentioned model as its provider does, without a thread", async () => {
436 + setup();
437 + await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", {
438 + environmentId: EnvironmentId.make("models"),
439 + });
440 +
441 + await expect
442 + .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" }))
443 + .toBeVisible();
444 + expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]);
445 + expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o.");
446 + });
447 });
448
449 describe("ChatMarkdown headings", () => {
apps/web/src/components/ChatMarkdown.tsx
+8 -4
@@ -978,8 +978,12 @@ const CHAT_MARKDOWN_COMPONENTS = {
978 return <div {...props}>{children}</div>;
979 },
980 p: function MarkdownParagraph({ node: _node, children, ...props }) {
981 - const { skills, threadRef } = use(ChatMarkdownRendererContext);
982 - return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills, threadRef)}</p>;
981 + const { skills, threadRef, environmentId } = use(ChatMarkdownRendererContext);
982 + return (
983 + <p {...props}>
984 + {renderSkillInlineMarkdownChildren(children, skills, threadRef, environmentId)}
985 + </p>
986 + );
987 },
988 blockquote: function MarkdownBlockquote({ node: _node, children, ...props }) {
989 const alert =
@@ -1014,12 +1018,12 @@ const CHAT_MARKDOWN_COMPONENTS = {
1018 );
1019 },
1020 li: function MarkdownListItem({ node, children, ...props }) {
1017 - const { skills, threadRef } = use(ChatMarkdownRendererContext);
1021 + const { skills, threadRef, environmentId } = use(ChatMarkdownRendererContext);
1022 // Resolve checkbox markers by offset to avoid rerendering list items on every streamed token.
1023 const isTaskItem = String(props.className ?? "").includes("task-list-item");
1024 return (
1025 <li {...props} data-list-item-offset={isTaskItem ? node?.position?.start.offset : undefined}>
1022 - {renderSkillInlineMarkdownChildren(children, skills, threadRef)}
1026 + {renderSkillInlineMarkdownChildren(children, skills, threadRef, environmentId)}
1027 </li>
1028 );
1029 },
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+75 -14
@@ -1,3 +1,4 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { documentChipKindForFileName } from "~/pierre-icons";
3 import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
4 import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
@@ -91,6 +92,7 @@ import {
92 skillChipReplacements,
93 splitOrLiftListItem,
94 stepCaretAcrossStyledEdge,
95 + type IsKnownModel,
96 type SkillMeta,
97 } from "~/composer-rich-text-doc";
98 import {
@@ -115,6 +117,7 @@ import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon";
117 import { FileTagChipContent } from "./chat/FileTagChip";
118 import { SkillChipPopover, skillPopoverDescription } from "./chat/SkillInlineText";
119 import { AssistantCitationChip } from "./chat/AssistantCitationChip";
120 +import { ModelMentionChip, modelMentionKey, modelMentionKeysAtom } from "./chat/ModelMentionChip";
121 import { getTimelinePageScrollKey } from "./chat/pageScrollController";
122 import { ContextChip } from "./ContextChip";
123 import {
@@ -327,6 +330,45 @@ const ComposerSkillExtension = Node.create({
330 },
331 });
332
333 +function ComposerModelNodeView({ node }: NodeViewProps) {
334 + const actions = use(ComposerContextActionsContext);
335 + return (
336 + <NodeViewWrapper as="span" className={CHIP_NODE_SELECTION_CLASS_NAME}>
337 + <ModelMentionChip
338 + environmentId={actions.environmentId}
339 + instanceId={String(node.attrs.instanceId)}
340 + model={String(node.attrs.model)}
341 + source={String(node.attrs.source)}
342 + />
343 + </NodeViewWrapper>
344 + );
345 +}
346 +
347 +/** `model:<instance>/<model>` from the `@` menu; `source` is the exact prompt text. */
348 +const ComposerModelExtension = Node.create({
349 + name: "composer-model",
350 + group: "inline",
351 + inline: true,
352 + atom: true,
353 + selectable: true,
354 + addAttributes() {
355 + return {
356 + instanceId: { default: "" },
357 + model: { default: "" },
358 + source: { default: "" },
359 + };
360 + },
361 + parseHTML() {
362 + return [{ tag: "span[data-composer-model]" }];
363 + },
364 + renderHTML({ HTMLAttributes }) {
365 + return ["span", { "data-composer-model": "", ...HTMLAttributes }];
366 + },
367 + addNodeView() {
368 + return ReactNodeViewRenderer(ComposerModelNodeView);
369 + },
370 +});
371 +
372 /** Chip presentation for `$name`, or null when the provider does not offer it to users. */
373 function composerSkillMeta(
374 skills: ReadonlyArray<ServerProviderSkill>,
@@ -772,6 +814,7 @@ function createComposerExtensions(richText: boolean) {
814 ComposerTextDirectionExtension,
815 ComposerMentionExtension,
816 ComposerSkillExtension,
817 + ComposerModelExtension,
818 ComposerCitationExtension,
819 ComposerContextReferenceExtension,
820 ComposerChipSelectionExtension,
@@ -913,8 +956,13 @@ function ComposerPromptEditorTiptapInner(
956 importContextFragment,
957 }));
958
916 - // Stable so a skills refresh does not rerun the controlled-value effect.
959 + const { environmentId } = use(ComposerContextActionsContext);
960 + const modelKeys = useAtomValue(modelMentionKeysAtom(environmentId ?? ""));
961 + // Stable so a skills or models refresh does not rerun the controlled-value effect.
962 const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name));
963 + const isKnownModel = useStableCallback((instanceId: string, model: string) =>
964 + modelKeys.has(modelMentionKey(instanceId, model)),
965 + );
966
967 const initialCursor = clampEditorCursor(value, cursor);
968 const initialExpandedCursor = Math.max(0, Math.min(value.length, props.initialExpandedCursor));
@@ -1043,6 +1091,7 @@ function ComposerPromptEditorTiptapInner(
1091 content: buildDocJson(value, (name) => composerSkillMeta(skills, name), {
1092 styling: richText,
1093 literalText,
1094 + isKnownModel: (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)),
1095 }),
1096 editable: !disabled,
1097 editorProps: {
@@ -1340,7 +1389,8 @@ function ComposerPromptEditorTiptapInner(
1389 const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`);
1390 const isChip = (token: (typeof tokens)[number] | undefined) =>
1391 token?.type === "mention" ||
1343 - (token?.type === "skill" && skillLabelFor(token.value) !== null);
1392 + (token?.type === "skill" && skillLabelFor(token.value) !== null) ||
1393 + (token?.type === "model" && isKnownModel(token.instanceId, token.model));
1394 const lastToken = tokens.at(-1);
1395 if (isChip(lastToken) && lastToken?.end === text.length) {
1396 text += " ";
@@ -1364,7 +1414,7 @@ function ComposerPromptEditorTiptapInner(
1414 insertMarkdownParagraphs(
1415 text,
1416 skillLabelFor,
1367 - { styling: richText, blocks: !nested, literalText, literalLength },
1417 + { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel },
1418 (content) => {
1419 editorInstance
1420 .chain()
@@ -1397,11 +1447,13 @@ function ComposerPromptEditorTiptapInner(
1447 },
1448 },
1449 onUpdate: ({ editor: updated, transaction }) => {
1400 - // Undo can restore a chip for a skill the current provider no longer offers.
1450 + // Undo can restore a chip for a skill or model the environment no longer offers.
1451 if (!literalText && isHistoryTransaction(transaction)) {
1402 - const stale = skillChipReplacements(updated.state.doc, skillLabelFor).filter(
1403 - ({ node }) => node.isText,
1404 - );
1452 + const stale = skillChipReplacements(
1453 + updated.state.doc,
1454 + skillLabelFor,
1455 + isKnownModel,
1456 + ).filter(({ node }) => node.isText);
1457 if (stale.length > 0) {
1458 replaceSkillChips(updated, stale);
1459 return;
@@ -1522,7 +1574,7 @@ function ComposerPromptEditorTiptapInner(
1574 if (previousSnapshot.value !== value) {
1575 saveCitationDraft(editor, previousSnapshot.value);
1576 editor.commands.setContent(
1525 - buildDocJson(value, skillLabelFor, { styling: richText, literalText }),
1577 + buildDocJson(value, skillLabelFor, { styling: richText, literalText, isKnownModel }),
1578 {
1579 emitUpdate: false,
1580 },
@@ -1563,18 +1615,21 @@ function ComposerPromptEditorTiptapInner(
1615 literalText,
1616 richText,
1617 skillLabelFor,
1618 + isKnownModel,
1619 value,
1620 ]);
1621
1569 - // Reconcile loaded or switched provider skills without rebuilding citation node views.
1570 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces skill chip nodes in the Tiptap document when the provider skill list loads or changes
1622 + // Reconcile loaded or switched provider skills and models without rebuilding citation node views.
1623 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces skill and model chip nodes in the Tiptap document when the provider skill or model list loads or changes
1624 useEffect(() => {
1625 if (!editor || literalText) return;
1573 - const replacements = skillChipReplacements(editor.state.doc, (name) =>
1574 - composerSkillMeta(skills, name),
1626 + const replacements = skillChipReplacements(
1627 + editor.state.doc,
1628 + (name) => composerSkillMeta(skills, name),
1629 + (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)),
1630 );
1631 if (replacements.length > 0) replaceSkillChips(editor, replacements);
1577 - }, [editor, literalText, skills]);
1632 + }, [editor, literalText, modelKeys, skills]);
1633
1634 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown
1635 useLayoutEffect(() => {
@@ -1804,7 +1859,13 @@ function ComposerPromptEditorTiptapInner(
1859 function insertMarkdownParagraphs(
1860 value: string,
1861 skillLabelFor: (name: string) => SkillMeta | null,
1807 - options: { styling: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number },
1862 + options: {
1863 + styling: boolean;
1864 + blocks?: boolean;
1865 + literalText?: boolean;
1866 + literalLength?: number;
1867 + isKnownModel?: IsKnownModel;
1868 + },
1869 insertContent: (content: JSONContent[] | JSONContent) => void,
1870 ): void {
1871 const blocks = buildTiptapContent(value, skillLabelFor, options);
apps/web/src/components/ContextChip.tsx
+1
@@ -26,6 +26,7 @@ const contextChipVariants = cva(
26 "pr-merged": "[--context-chip-accent:var(--context-chip-pr-merged)]",
27 "pr-closed": "[--context-chip-accent:var(--context-chip-pr-closed)]",
28 skill: "[--context-chip-accent:var(--context-chip-skill)]",
29 + model: "[--context-chip-accent:var(--context-chip-model)]",
30 thread: "[--context-chip-accent:var(--context-chip-thread)]",
31 environment: "[--context-chip-accent:var(--context-chip-environment)]",
32 citation: "[--context-chip-accent:var(--context-chip-citation)]",
apps/web/src/components/chat/ChatComposer.tsx
+18
@@ -47,6 +47,7 @@ import {
47 import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
48 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
49 import * as Schema from "effect/Schema";
50 +import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions";
51 import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
52 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
53 import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
@@ -1102,6 +1103,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1103 showSkillsInSlashMenu: settings.showSkillsInSlashMenu,
1104 workspaceSkillsScanning,
1105 questionAttachmentTarget,
1106 + modelMentions: { instanceEntries: providerInstanceEntries, modelOptionsByInstance },
1107 });
1108
1109 const composerMenuOpen = Boolean(composerTrigger);
@@ -1983,6 +1985,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1985 }
1986 return;
1987 }
1988 + if (item.type === "model") {
1989 + if (trigger.kind !== "path") return;
1990 + const replacement = `${formatComposerModelMention(item.instanceId, item.model)} `;
1991 + const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
1992 + snapshot.value,
1993 + trigger.rangeEnd,
1994 + replacement,
1995 + );
1996 + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, {
1997 + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd),
1998 + });
1999 + if (applied) {
2000 + setComposerHighlightedItemId(null);
2001 + }
2002 + return;
2003 + }
2004 if (item.type === "environment") {
2005 if (trigger.kind !== "path") return;
2006 const record = environmentContextRecord(item.environmentId, item.label);
apps/web/src/components/chat/ComposerCommandMenu.tsx
+24
@@ -9,6 +9,7 @@ import {
9 type EnvironmentMachineKind,
10 type ProjectEntry,
11 type ProviderDriverKind,
12 + type ProviderInstanceId,
13 type PullRequestContextMetadata,
14 type ScopedThreadRef,
15 type ServerProviderSkill,
@@ -31,6 +32,7 @@ import { Badge } from "../ui/badge";
32 import { Command, CommandGroup, CommandItem, CommandList } from "../ui/command";
33 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
34 import { PierreEntryIcon } from "./PierreEntryIcon";
35 +import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
36 import { ComposerBanner } from "./ComposerBanner";
37 import { resolvePullRequestState } from "../pullRequest/pullRequestPresentation";
38
@@ -88,6 +90,18 @@ export type ComposerCommandItem =
90 machine: EnvironmentMachineKind;
91 label: string;
92 description: string;
93 + }
94 + | {
95 + id: string;
96 + type: "model";
97 + instanceId: ProviderInstanceId;
98 + model: string;
99 + driverKind: ProviderDriverKind;
100 + providerDisplayName: string;
101 + acpRegistryAgentId: string | undefined;
102 + acpRegistryIconUrl: string | undefined;
103 + label: string;
104 + description: string;
105 };
106
107 export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
@@ -221,6 +235,16 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
235 className="size-4 shrink-0 text-secondary-label"
236 />
237 ) : null}
238 + {props.item.type === "model" ? (
239 + <ProviderInstanceIcon
240 + driverKind={props.item.driverKind}
241 + displayName={props.item.providerDisplayName}
242 + acpRegistryAgentId={props.item.acpRegistryAgentId}
243 + acpRegistryIconUrl={props.item.acpRegistryIconUrl}
244 + className="size-4 shrink-0"
245 + iconClassName="size-4"
246 + />
247 + ) : null}
248 {pullRequestPresentation ? (
249 <pullRequestPresentation.Icon
250 role="img"
apps/web/src/components/chat/ModelMentionChip.tsx new
+125
@@ -0,0 +1,125 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import type { EnvironmentId, ProviderDriverKind } from "@t3tools/contracts";
3 +import * as Option from "effect/Option";
4 +import { Atom } from "effect/reactivity";
5 +
6 +import { brandProviderInstanceEntries, deriveProviderInstanceEntries } from "~/providerInstances";
7 +import { serverEnvironment } from "~/state/server";
8 +import { contextChipAccentWithHueOf } from "~/themePalette";
9 +import { ContextChipPopover } from "../contextChipParts";
10 +import { ProviderInstanceIcon, providerLogoColor } from "./ProviderInstanceIcon";
11 +import { getDisplayModelName } from "./providerIconUtils";
12 +
13 +interface ModelMentionPresentation {
14 + readonly label: string;
15 + readonly providerLabel: string;
16 + readonly driverKind: ProviderDriverKind;
17 + readonly providerDisplayName: string;
18 + readonly acpRegistryAgentId: string | undefined;
19 + readonly acpRegistryIconUrl: string | undefined;
20 +}
21 +
22 +function presentationsEqual(left: ModelMentionPresentation, right: ModelMentionPresentation) {
23 + return (
24 + left.label === right.label &&
25 + left.providerLabel === right.providerLabel &&
26 + left.driverKind === right.driverKind &&
27 + left.providerDisplayName === right.providerDisplayName &&
28 + left.acpRegistryAgentId === right.acpRegistryAgentId &&
29 + left.acpRegistryIconUrl === right.acpRegistryIconUrl
30 + );
31 +}
32 +
33 +// Keyed per mention so provider status pushes don't rerender every message that names a model.
34 +const modelMentionPresentationAtom = Atom.family((key: string) =>
35 + Atom.make((get): ModelMentionPresentation | null => {
36 + const [environmentId, instanceId, model] = key.split("\u0000") as [string, string, string];
37 + if (!environmentId) return null;
38 + const config = get(serverEnvironment.configValueAtom(environmentId as EnvironmentId));
39 + const provider = config?.providers.find((candidate) => candidate.instanceId === instanceId);
40 + const option = provider?.models.find((candidate) => candidate.slug === model);
41 + if (!config || !provider || !option) return null;
42 + const [entry] = brandProviderInstanceEntries(
43 + deriveProviderInstanceEntries([provider]),
44 + config.settings,
45 + );
46 + if (!entry) return null;
47 + const next: ModelMentionPresentation = {
48 + label: getDisplayModelName(option),
49 + providerLabel: option.subProvider ?? entry.displayName,
50 + driverKind: entry.driverKind,
51 + providerDisplayName: entry.displayName,
52 + acpRegistryAgentId: entry.acpRegistryAgentId,
53 + acpRegistryIconUrl: entry.acpRegistryIconUrl,
54 + };
55 + const previous = Option.getOrNull(get.self<ModelMentionPresentation | null>());
56 + return previous && presentationsEqual(previous, next) ? previous : next;
57 + }).pipe(Atom.withLabel("model-mention-presentation")),
58 +);
59 +
60 +export function modelMentionKey(instanceId: string, model: string): string {
61 + return `${instanceId}\u0000${model}`;
62 +}
63 +
64 +// Keeps its identity until the environment's models change, so status pushes don't reconcile the composer.
65 +export const modelMentionKeysAtom = Atom.family((environmentId: string) =>
66 + Atom.make((get): ReadonlySet<string> => {
67 + const config = environmentId
68 + ? get(serverEnvironment.configValueAtom(environmentId as EnvironmentId))
69 + : null;
70 + const next = new Set(
71 + config?.providers.flatMap((provider) =>
72 + provider.models.map((option) => modelMentionKey(provider.instanceId, option.slug)),
73 + ),
74 + );
75 + const previous = Option.getOrNull(get.self<ReadonlySet<string>>());
76 + return previous && previous.size === next.size && [...next].every((key) => previous.has(key))
77 + ? previous
78 + : next;
79 + }).pipe(Atom.withLabel("model-mention-keys")),
80 +);
81 +
82 +function logoAccent(driverKind: ProviderDriverKind): string | undefined {
83 + const color = providerLogoColor(driverKind);
84 + return (color && contextChipAccentWithHueOf("model", color)) || undefined;
85 +}
86 +
87 +export function ModelMentionChip(props: {
88 + environmentId: EnvironmentId | null;
89 + instanceId: string;
90 + model: string;
91 + source: string;
92 +}) {
93 + const presentation = useAtomValue(
94 + modelMentionPresentationAtom(
95 + `${props.environmentId ?? ""}\u0000${modelMentionKey(props.instanceId, props.model)}`,
96 + ),
97 + );
98 + if (!presentation) return props.source;
99 + const accent = logoAccent(presentation.driverKind);
100 + return (
101 + <ContextChipPopover
102 + kind="neutral"
103 + accent={accent}
104 + icon={
105 + <ProviderInstanceIcon
106 + driverKind={presentation.driverKind}
107 + displayName={presentation.providerDisplayName}
108 + acpRegistryAgentId={presentation.acpRegistryAgentId}
109 + acpRegistryIconUrl={presentation.acpRegistryIconUrl}
110 + className="z-auto"
111 + iconClassName="size-[1em]"
112 + />
113 + }
114 + label={presentation.label}
115 + accessibleLabel={`Model ${presentation.label}`}
116 + copyMarkdown={props.source}
117 + >
118 + <div className="space-y-1 p-2 text-sm">
119 + <p className="font-medium">{presentation.label}</p>
120 + <p className="text-muted-foreground">{presentation.providerLabel}</p>
121 + <p className="font-mono text-xs text-muted-foreground">{props.source}</p>
122 + </div>
123 + </ContextChipPopover>
124 + );
125 +}
apps/web/src/components/chat/ModelPickerContent.tsx
+1 -1
@@ -30,7 +30,7 @@ import {
30 parseModelPickerLegacySectionKey,
31 parseModelPickerModelKey,
32 } from "./modelPickerKeys";
33 -import { rankModelPickerSearch } from "./modelPickerSearch";
33 +import { rankModelPickerSearch } from "@t3tools/client-runtime/model-search";
34 import {
35 Combobox,
36 ComboboxEmpty,
apps/web/src/components/chat/ProviderInstanceIcon.tsx
+12
@@ -47,6 +47,18 @@ const PROVIDER_TEXT_COLOR_BY_PROVIDER: Partial<Record<ProviderDriverKind, string
47 [ProviderDriverKind.make("ollama")]: "text-black dark:text-white",
48 };
49
50 +const BUNDLED_LOGO_COLOR_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
51 + [ProviderDriverKind.make("claudeAgent")]: "#d97757",
52 + [ProviderDriverKind.make("antigravity")]: "#5b87bf",
53 +};
54 +
55 +/** The logo's own color, or null for logos that swap between black and white per theme. */
56 +export function providerLogoColor(driverKind: ProviderDriverKind): string | null {
57 + const fill = providerClients.get(driverKind)?.icon?.fill;
58 + if (fill) return fill.light === fill.dark ? fill.light : null;
59 + return BUNDLED_LOGO_COLOR_BY_PROVIDER[driverKind] ?? null;
60 +}
61 +
62 export function providerTextColor(driverKind: ProviderDriverKind): {
63 readonly className?: string;
64 readonly style?: CSSProperties;
apps/web/src/components/chat/SkillInlineText.tsx
+55 -21
@@ -1,4 +1,5 @@
1 -import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
1 +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions";
2 +import type { EnvironmentId, ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
3 import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
4 import { Children, cloneElement, isValidElement, type ReactNode } from "react";
5 import { matchInlineSkills } from "@t3tools/shared/inlineSkills";
@@ -7,34 +8,59 @@ import { useRightPanelStore } from "~/rightPanelStore";
8 import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip";
9 import { ContextChipPopover } from "../contextChipParts";
10 import { Button } from "../ui/button";
11 +import { ModelMentionChip } from "./ModelMentionChip";
12
13 function SkillInlineText(props: {
14 text: string;
15 skills: ReadonlyArray<ServerProviderSkill>;
16 threadRef: ScopedThreadRef | undefined;
17 + environmentId: EnvironmentId | null;
18 }) {
16 - const nodes: ReactNode[] = [];
17 - let cursor = 0;
18 -
19 + const chips: Array<{ start: number; end: number; node: ReactNode }> = [];
20 for (const { start, end, skill, rawText } of matchInlineSkills(props.text, props.skills)) {
20 - if (start > cursor) {
21 - nodes.push(props.text.slice(cursor, start));
22 - }
23 - nodes.push(
24 - <SkillChipPopover
25 - key={`${start}:${skill.name}`}
26 - label={formatProviderSkillDisplayName(skill)}
27 - description={skillPopoverDescription(skill)}
28 - copyMarkdown={rawText}
29 - onViewInstructions={skillInstructionsOpener(props.threadRef, skill)}
30 - />,
31 - );
32 - cursor = end;
21 + chips.push({
22 + start,
23 + end,
24 + node: (
25 + <SkillChipPopover
26 + key={`${start}:${skill.name}`}
27 + label={formatProviderSkillDisplayName(skill)}
28 + description={skillPopoverDescription(skill)}
29 + copyMarkdown={rawText}
30 + onViewInstructions={skillInstructionsOpener(props.threadRef, skill)}
31 + />
32 + ),
33 + });
34 }
34 -
35 - if (cursor === 0) {
35 + for (const mention of collectComposerModelMentions(props.text)) {
36 + chips.push({
37 + start: mention.start,
38 + end: mention.end,
39 + node: (
40 + <ModelMentionChip
41 + key={`${mention.start}:model`}
42 + environmentId={props.environmentId}
43 + instanceId={mention.instanceId}
44 + model={mention.model}
45 + source={mention.source}
46 + />
47 + ),
48 + });
49 + }
50 + if (chips.length === 0) {
51 return <>{props.text}</>;
52 }
53 +
54 + const nodes: ReactNode[] = [];
55 + let cursor = 0;
56 + for (const chip of chips.toSorted((left, right) => left.start - right.start)) {
57 + if (chip.start < cursor) continue;
58 + if (chip.start > cursor) {
59 + nodes.push(props.text.slice(cursor, chip.start));
60 + }
61 + nodes.push(chip.node);
62 + cursor = chip.end;
63 + }
64 if (cursor < props.text.length) {
65 nodes.push(props.text.slice(cursor));
66 }
@@ -45,10 +71,18 @@ export function renderSkillInlineMarkdownChildren(
71 children: ReactNode,
72 skills: ReadonlyArray<ServerProviderSkill>,
73 threadRef: ScopedThreadRef | undefined,
74 + environmentId: EnvironmentId | null,
75 ): ReactNode {
76 return Children.map(children, (child) => {
77 if (typeof child === "string") {
51 - return <SkillInlineText text={child} skills={skills} threadRef={threadRef} />;
78 + return (
79 + <SkillInlineText
80 + text={child}
81 + skills={skills}
82 + threadRef={threadRef}
83 + environmentId={environmentId}
84 + />
85 + );
86 }
87 if (!isValidElement<{ children?: ReactNode; node?: { tagName?: string } }>(child)) {
88 return child;
@@ -64,7 +98,7 @@ export function renderSkillInlineMarkdownChildren(
98 return cloneElement(
99 child,
100 undefined,
67 - renderSkillInlineMarkdownChildren(child.props.children, skills, threadRef),
101 + renderSkillInlineMarkdownChildren(child.props.children, skills, threadRef, environmentId),
102 );
103 });
104 }
apps/web/src/components/chat/composerModelMentions.ts new
+43
@@ -0,0 +1,43 @@
1 +import { rankComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions";
2 +import type { ProviderInstanceId } from "@t3tools/contracts";
3 +
4 +import { isProviderInstancePickerReady, type ProviderInstanceEntry } from "../../providerInstances";
5 +import type { ComposerCommandItem } from "./ComposerCommandMenu";
6 +import { getDisplayModelName, type ModelEsque } from "./providerIconUtils";
7 +
8 +type ComposerModelItem = Extract<ComposerCommandItem, { type: "model" }>;
9 +
10 +export function matchComposerModelItems(input: {
11 + readonly instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
12 + readonly modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
13 + readonly query: string;
14 +}): ComposerModelItem[] {
15 + const candidates: Array<{ entry: ProviderInstanceEntry; option: ModelEsque }> = [];
16 + for (const entry of input.instanceEntries) {
17 + if (!isProviderInstancePickerReady(entry)) continue;
18 + for (const option of input.modelOptionsByInstance.get(entry.instanceId) ?? []) {
19 + // The picker hides legacy models by default; skip them so they don't fill the result cap.
20 + if (option.isLegacy || option.isUnavailable) continue;
21 + candidates.push({ entry, option });
22 + }
23 + }
24 +
25 + return rankComposerModelMentions(candidates, input.query, ({ entry, option }) => ({
26 + name: option.name,
27 + ...(option.shortName ? { shortName: option.shortName } : {}),
28 + ...(option.subProvider ? { subProvider: option.subProvider } : {}),
29 + driverKind: entry.driverKind,
30 + providerDisplayName: entry.displayName,
31 + })).map(({ entry, option }) => ({
32 + id: `model:${entry.instanceId}:${option.slug}`,
33 + type: "model",
34 + instanceId: entry.instanceId,
35 + model: option.slug,
36 + driverKind: entry.driverKind,
37 + providerDisplayName: entry.displayName,
38 + acpRegistryAgentId: entry.acpRegistryAgentId,
39 + acpRegistryIconUrl: entry.acpRegistryIconUrl,
40 + label: getDisplayModelName(option),
41 + description: option.subProvider ?? entry.displayName,
42 + }));
43 +}
apps/web/src/components/chat/useComposerMenuItems.ts
+14
@@ -8,6 +8,7 @@ import type {
8 EnvironmentId,
9 ProjectId,
10 ProviderDriverKind,
11 + ProviderInstanceId,
12 PullRequestListInput,
13 ServerProvider,
14 ThreadId,
@@ -43,6 +44,9 @@ import {
44 rankPullRequestMatches,
45 } from "../pullRequest/pullRequestList.logic";
46 import type { ComposerCommandItem } from "./ComposerCommandMenu";
47 +import { matchComposerModelItems } from "./composerModelMentions";
48 +import type { ModelEsque } from "./providerIconUtils";
49 +import type { ProviderInstanceEntry } from "../../providerInstances";
50 import {
51 searchSlashCommandItems,
52 slashCommandItemsForPromptPosition,
@@ -73,6 +77,7 @@ export function useComposerMenuItems({
77 showSkillsInSlashMenu,
78 workspaceSkillsScanning,
79 questionAttachmentTarget,
80 + modelMentions,
81 }: {
82 readonly composerTrigger: ComposerTrigger | null;
83 readonly environmentId: EnvironmentId;
@@ -92,6 +97,10 @@ export function useComposerMenuItems({
97 readonly showSkillsInSlashMenu: boolean;
98 readonly workspaceSkillsScanning: boolean;
99 readonly questionAttachmentTarget: DraftId | null;
100 + readonly modelMentions: {
101 + readonly instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
102 + readonly modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
103 + };
104 }) {
105 // Thread mentions rank by recency as of when the composer mounted.
106 const [now] = useState(() => Date.now());
@@ -204,6 +213,11 @@ export function useComposerMenuItems({
213 query: composerTrigger.query,
214 })
215 : []),
216 + ...matchComposerModelItems({
217 + instanceEntries: modelMentions.instanceEntries,
218 + modelOptionsByInstance: modelMentions.modelOptionsByInstance,
219 + query: composerTrigger.query,
220 + }),
221 ...workspaceEntries.entries.map((entry) => ({
222 id: `path:${entry.kind}:${entry.path}`,
223 type: "path" as const,
apps/web/src/components/contextChipParts.tsx
+15 -1
@@ -1,6 +1,13 @@
1 import type { EnvironmentId, PullRequestContextMetadata } from "@t3tools/contracts";
2 import { CircleDashedIcon, FilmIcon, ImageIcon } from "lucide-react";
3 -import { useEffect, useState, type ComponentProps, type MouseEvent, type ReactNode } from "react";
3 +import {
4 + useEffect,
5 + useState,
6 + type ComponentProps,
7 + type CSSProperties,
8 + type MouseEvent,
9 + type ReactNode,
10 +} from "react";
11 import { useAssetUrlState } from "~/assets/assetUrls";
12 import { documentChipKindForFileName } from "~/pierre-icons";
13
@@ -60,6 +67,8 @@ export function ContextChipPopover(props: {
67 label: string;
68 copyMarkdown?: string | undefined;
69 accessibleLabel: string;
70 + /** Overrides the kind's accent color. */
71 + accent?: string | undefined;
72 children: ReactNode;
73 }) {
74 return (
@@ -68,6 +77,11 @@ export function ContextChipPopover(props: {
77 render={
78 <ContextChip
79 kind={props.kind}
80 + style={
81 + props.accent
82 + ? ({ "--context-chip-accent": props.accent } as CSSProperties)
83 + : undefined
84 + }
85 render={<button type="button" />}
86 aria-label={`${props.accessibleLabel}. Show details`}
87 data-markdown-copy={props.copyMarkdown}
apps/web/src/composer-editor-mentions.ts
+35 -1
@@ -1,8 +1,10 @@
1 +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions";
2 import type { AssistantCitation } from "@t3tools/contracts";
3 import { collectAssistantCitations } from "@t3tools/shared/assistantCitations";
4 import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
5 import {
6 collectComposerInlineTokens,
7 + composerMathRanges,
8 type ComposerInlineToken,
9 } from "@t3tools/shared/composerInlineTokens";
10
@@ -21,6 +23,12 @@ export type ComposerPromptSegment =
23 name: string;
24 source: string;
25 }
26 + | {
27 + type: "model";
28 + instanceId: string;
29 + model: string;
30 + source: string;
31 + }
32 | {
33 type: "citation";
34 citation: AssistantCitation;
@@ -75,8 +83,27 @@ function forEachMentionMatch(
83 });
84 }
85
86 +// Like `$skill`, a typed reference waits for whitespace so `gpt-6` cannot chip while typing `gpt-6.1`.
87 +function collectModelTokens(text: string, inlineTokens: ReadonlyArray<ComposerInlineToken>) {
88 + const mentions = collectComposerModelMentions(text).filter((mention) =>
89 + /\s/.test(text[mention.end] ?? ""),
90 + );
91 + if (mentions.length === 0) return [];
92 + const taken = [...inlineTokens, ...composerMathRanges(text)];
93 + return mentions
94 + .filter(
95 + (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start),
96 + )
97 + .map((mention) => ({ ...mention, type: "model" as const }));
98 +}
99 +
100 export function collectComposerPromptInlineTokens(text: string) {
79 - const tokens = collectComposerInlineTokens(text);
101 + const inlineTokens = collectComposerInlineTokens(text);
102 + const models = collectModelTokens(text, inlineTokens);
103 + const tokens =
104 + models.length === 0
105 + ? inlineTokens
106 + : [...inlineTokens, ...models].sort((left, right) => left.start - right.start);
107 const citations = collectAssistantCitations(text);
108 const references = collectComposerContextReferences(text);
109 if (citations.length === 0 && references.length === 0) return tokens;
@@ -127,6 +154,13 @@ function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegmen
154 path: match.value,
155 source: match.source,
156 });
157 + } else if (match.type === "model") {
158 + segments.push({
159 + type: "model",
160 + instanceId: match.instanceId,
161 + model: match.model,
162 + source: match.source,
163 + });
164 } else {
165 segments.push({ type: "skill", name: match.value, source: match.source });
166 }
apps/web/src/composer-logic.ts
+2 -2
@@ -138,7 +138,7 @@ export function expandCollapsedComposerCursor(
138 expandedCursor += expandedLength;
139 continue;
140 }
141 - if (segment.type === "skill") {
141 + if (segment.type === "skill" || segment.type === "model") {
142 const expandedLength = segment.source.length;
143 if (remaining <= 1) {
144 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
@@ -224,7 +224,7 @@ export function collapseExpandedComposerCursor(
224 collapsedCursor += 1;
225 continue;
226 }
227 - if (segment.type === "skill") {
227 + if (segment.type === "skill" || segment.type === "model") {
228 const expandedLength = segment.source.length;
229 if (remaining === 0) {
230 return collapsedCursor;
apps/web/src/composer-rich-text-doc.test.ts
+66 -4
@@ -67,6 +67,11 @@ const schema = getSchemaByResolvedExtensions(
67 skillLabel: { default: "" },
68 skillDescription: { default: null },
69 }),
70 + stubAtom("composer-model", {
71 + instanceId: { default: "" },
72 + model: { default: "" },
73 + source: { default: "" },
74 + }),
75 stubAtom("composer-citation", {
76 citation: { default: null },
77 source: { default: "" },
@@ -188,6 +193,11 @@ const plainSchema = getSchemaByResolvedExtensions(
193 skillLabel: { default: "" },
194 skillDescription: { default: null },
195 }),
196 + stubAtom("composer-model", {
197 + instanceId: { default: "" },
198 + model: { default: "" },
199 + source: { default: "" },
200 + }),
201 stubAtom("composer-citation", {
202 citation: { default: null },
203 source: { default: "" },
@@ -747,17 +757,21 @@ describe("composer rich text document model", () => {
757 });
758
759 it("keeps a chip's source in a fence as literal text", () => {
750 - const value = "```\nsee @b.md and $babysit now\n```\nafter";
760 + const value = "```\nsee @b.md and $babysit now model:codex/gpt-6.1 ok\n```\nafter";
761 const known = () => ({ label: "Babysit", description: null });
752 - const doc = ProseMirrorNode.fromJSON(schema, buildDocJson(value, known));
762 + const anyModel = () => true;
763 + const doc = ProseMirrorNode.fromJSON(
764 + schema,
765 + buildDocJson(value, known, { isKnownModel: anyModel }),
766 + );
767 const map = serializeEditorDoc(doc);
768 expect(map.value).toBe(value);
769 expect(map.runs.filter((run) => run.kind === "token")).toEqual([]);
770 for (let flat = 0; flat <= map.docLength; flat += 1) {
771 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
772 }
759 - // Reconciling against the provider's skills leaves the code alone too.
760 - expect(skillChipReplacements(doc, known)).toEqual([]);
773 + // Reconciling against the provider's skills and models leaves the code alone too.
774 + expect(skillChipReplacements(doc, known, anyModel)).toEqual([]);
775 });
776
777 it.each([
@@ -831,6 +845,54 @@ describe("pasting into a list item or quote", () => {
845 });
846 });
847
848 +describe("model mention chips", () => {
849 + const skillLabelFor = (name: string) => ({ label: name, description: null });
850 + const isCodexModel = (instanceId: string, model: string) =>
851 + instanceId === "codex" && model === "gpt-6.1";
852 + const modelAttrs = (doc: ProseMirrorNode) => {
853 + const attrs: unknown[] = [];
854 + doc.descendants((node) => {
855 + if (node.type.name === "composer-model") attrs.push(node.attrs);
856 + });
857 + return attrs;
858 + };
859 + const replace = (doc: ProseMirrorNode, isKnownModel?: typeof isCodexModel) => {
860 + const transaction = EditorState.create({ doc }).tr;
861 + for (const { from, to, node } of skillChipReplacements(doc, skillLabelFor, isKnownModel)) {
862 + transaction.replaceWith(from, to, node);
863 + }
864 + return transaction.doc;
865 + };
866 + const chip = { instanceId: "codex", model: "gpt-6.1", source: "model:codex/gpt-6.1" };
867 +
868 + it.each([
869 + ["Ask model:codex/gpt-6.1 now", [chip]],
870 + ["Ask model:openai/gpt-4o now", []],
871 + // Still being typed: `gpt-6` must not chip on the way to `gpt-6.1`.
872 + ["Ask model:codex/gpt-6.1", []],
873 + ])("chips only a known reference followed by whitespace: %s", (value, expected) => {
874 + const doc = ProseMirrorNode.fromJSON(
875 + schema,
876 + buildDocJson(value, skillLabelFor, { isKnownModel: isCodexModel }),
877 + );
878 + doc.check();
879 + expect(modelAttrs(doc)).toEqual(expected);
880 + expect(serializeEditorDoc(doc).value).toBe(value);
881 + });
882 +
883 + it("reconciles references when the environment's models load or change", () => {
884 + const value = "Ask model:codex/gpt-6.1 now";
885 + const text = ProseMirrorNode.fromJSON(schema, buildDocJson(value, skillLabelFor));
886 + expect(modelAttrs(text)).toEqual([]);
887 + const loaded = replace(text, isCodexModel);
888 + expect(modelAttrs(loaded)).toEqual([chip]);
889 + expect(serializeEditorDoc(loaded).value).toBe(value);
890 + const removed = replace(loaded);
891 + expect(modelAttrs(removed)).toEqual([]);
892 + expect(serializeEditorDoc(removed).value).toBe(value);
893 + });
894 +});
895 +
896 describe("pasting into a path query", () => {
897 const skillLabelFor = (name: string) => ({ label: name, description: null });
898
apps/web/src/composer-rich-text-doc.ts
+54 -26
@@ -53,6 +53,15 @@ import { composerMathRanges } from "@t3tools/shared/composerInlineTokens";
53
54 export type SkillMeta = { label: string; description: string | null };
55
56 +export type IsKnownModel = (instanceId: string, model: string) => boolean;
57 +
58 +interface ChipResolver {
59 + skill: (name: string) => SkillMeta | null;
60 + model: IsKnownModel;
61 +}
62 +
63 +const NO_MODELS: IsKnownModel = () => false;
64 +
65 const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];
66
67 const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
@@ -611,17 +620,18 @@ function listKey(prefix: ListLinePrefix): string {
620 }
621
622 type InlineJson = Record<string, unknown>;
623 +type AtomJson = { type: string; attrs: Record<string, unknown> };
624
625 interface DocLine {
626 list: ListLinePrefix | null;
627 inline: InlineJson[];
628 }
629
620 -/** Null for a `$name` that is not one of the provider's skills: it stays editable text. */
630 +/** Null for a `$name` or `model:` reference the resolver does not know: it stays editable text. */
631 function atomJsonForSegment(
632 segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
623 - skillLabelFor: (name: string) => SkillMeta | null,
624 -): InlineJson | null {
633 + chips: ChipResolver,
634 +): AtomJson | null {
635 if (segment.type === "mention") {
636 return {
637 type: "composer-mention",
@@ -629,7 +639,7 @@ function atomJsonForSegment(
639 };
640 }
641 if (segment.type === "skill") {
632 - const meta = skillLabelFor(segment.name);
642 + const meta = chips.skill(segment.name);
643 if (!meta) return null;
644 return {
645 type: "composer-skill",
@@ -640,6 +650,13 @@ function atomJsonForSegment(
650 },
651 };
652 }
653 + if (segment.type === "model") {
654 + if (!chips.model(segment.instanceId, segment.model)) return null;
655 + return {
656 + type: "composer-model",
657 + attrs: { instanceId: segment.instanceId, model: segment.model, source: segment.source },
658 + };
659 + }
660 if (segment.type === "citation") {
661 return {
662 type: "composer-citation",
@@ -718,8 +735,15 @@ function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, un
735 export function buildTiptapContent(
736 value: string,
737 skillLabelFor: (name: string) => SkillMeta | null,
721 - options?: { styling?: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number },
738 + options?: {
739 + styling?: boolean;
740 + blocks?: boolean;
741 + literalText?: boolean;
742 + literalLength?: number;
743 + isKnownModel?: IsKnownModel;
744 + },
745 ): Record<string, unknown>[] {
746 + const chips = { skill: skillLabelFor, model: options?.isKnownModel ?? NO_MODELS };
747 if (options?.literalText) {
748 return value.split("\n").map((line) => ({
749 type: "paragraph",
@@ -756,7 +780,7 @@ export function buildTiptapContent(
780 return splitPromptIntoComposerSegments(chunk.text)
781 .map((segment) => {
782 if (segment.type === "text") return segment.text;
759 - const atom = atomJsonForSegment(segment, skillLabelFor);
783 + const atom = atomJsonForSegment(segment, chips);
784 if (!atom) return segment.source;
785 atoms.push(atom);
786 atomSources.push(segment.source);
@@ -956,7 +980,7 @@ export function buildTiptapContent(
980 export function buildDocJson(
981 value: string,
982 skillLabelFor: (name: string) => SkillMeta | null,
959 - options?: { styling?: boolean; literalText?: boolean },
983 + options?: { styling?: boolean; literalText?: boolean; isKnownModel?: IsKnownModel },
984 ) {
985 const content = buildTiptapContent(value, skillLabelFor, options);
986 if (content.at(-1)?.type === "horizontalRule") content.push({ type: "paragraph" });
@@ -989,6 +1013,7 @@ function readAtomSource(node: ProseMirrorNode): string {
1013 const attrs = node.attrs as Record<string, unknown>;
1014 switch (node.type.name) {
1015 case "composer-mention":
1016 + case "composer-model":
1017 case "composer-citation":
1018 case "composer-context-reference":
1019 return typeof attrs.source === "string" ? attrs.source : "";
@@ -1539,6 +1564,15 @@ export interface SkillChipReplacement {
1564 node: ProseMirrorNode;
1565 }
1566
1567 +function isStaleChip(node: ProseMirrorNode, chips: ChipResolver): boolean {
1568 + const { skillName, instanceId, model } = node.attrs as Record<string, unknown>;
1569 + if (node.type.name === "composer-skill") {
1570 + return typeof skillName === "string" && skillName !== "" && !chips.skill(skillName);
1571 + }
1572 + if (node.type.name === "composer-model") return !chips.model(String(instanceId), String(model));
1573 + return false;
1574 +}
1575 +
1576 /**
1577 * Use the same Markdown token boundaries as draft restoration. Apply edits
1578 * last-first so positions stay valid and unrelated citation nodes keep their keys.
@@ -1546,30 +1580,28 @@ export interface SkillChipReplacement {
1580 export function skillChipReplacements(
1581 doc: ProseMirrorNode,
1582 skillLabelFor: (name: string) => SkillMeta | null,
1583 + isKnownModel: IsKnownModel = NO_MODELS,
1584 ): SkillChipReplacement[] {
1585 + const chips = { skill: skillLabelFor, model: isKnownModel };
1586 const schema = doc.type.schema;
1551 - const skillType = schema.nodes["composer-skill"];
1552 - if (!skillType) return [];
1587 const replacements: SkillChipReplacement[] = [];
1588 doc.descendants((node, pos) => {
1555 - if (node.type !== skillType) return;
1556 - const name = typeof node.attrs.skillName === "string" ? node.attrs.skillName : "";
1557 - if (name && !skillLabelFor(name)) {
1558 - replacements.push({
1559 - from: pos,
1560 - to: pos + node.nodeSize,
1561 - node: schema.text(readAtomSource(node), node.marks),
1562 - });
1563 - }
1589 + if (!isStaleChip(node, chips)) return;
1590 + replacements.push({
1591 + from: pos,
1592 + to: pos + node.nodeSize,
1593 + node: schema.text(readAtomSource(node), node.marks),
1594 + });
1595 });
1596 const map = serializeEditorDoc(doc);
1597 let end = 0;
1598 for (const segment of splitPromptIntoComposerSegments(map.value)) {
1599 const start = end;
1600 end += segment.type === "text" ? segment.text.length : segment.source.length;
1570 - if (segment.type !== "skill") continue;
1571 - const meta = skillLabelFor(segment.name);
1572 - if (!meta) continue;
1601 + if (segment.type !== "skill" && segment.type !== "model") continue;
1602 + const atom = atomJsonForSegment(segment, chips);
1603 + const type = atom && schema.nodes[atom.type];
1604 + if (!atom || !type) continue;
1605 // Only text needs converting; an existing chip is a token run.
1606 const run = map.runs.find(
1607 (candidate) =>
@@ -1583,11 +1615,7 @@ export function skillChipReplacements(
1615 replacements.push({
1616 from,
1617 to: from + segment.source.length,
1586 - node: skillType.create(
1587 - { skillName: segment.name, skillLabel: meta.label, skillDescription: meta.description },
1588 - null,
1589 - doc.nodeAt(from)?.marks,
1590 - ),
1618 + node: type.create(atom.attrs, null, doc.nodeAt(from)?.marks),
1619 });
1620 }
1621 return replacements.sort((left, right) => right.from - left.from);
apps/web/src/lib/contextChipAccents.ts
+1
@@ -13,6 +13,7 @@ export const CONTEXT_CHIP_ACCENTS = {
13 "pr-merged": "oklch(0.62 0.16 292)",
14 "pr-closed": "oklch(0.62 0.16 16)",
15 skill: "oklch(0.62 0.16 322)",
16 + model: "oklch(0.62 0.13 105)",
17 thread: "oklch(0.62 0.12 190)",
18 environment: "oklch(0.62 0.11 145)",
19 citation: "oklch(0.62 0.16 259)",
apps/web/src/themePalette.ts
+11
@@ -676,6 +676,17 @@ export function readableThemeColorOn(color: string, surface: string, minContrast
676 return themeRgbToHexColor(themeOklchToRgb(solved));
677 }
678
679 +/** A chip kind's per-theme contrast-solved lightness with `color`'s hue and chroma. */
680 +export function contextChipAccentWithHueOf(
681 + kind: ContextChipAccentKind,
682 + color: string,
683 +): string | null {
684 + const parsed = parseThemeColor(color);
685 + if (!parsed) return null;
686 + const { C, h } = parsed.color;
687 + return `oklch(from var(${contextChipColorVariable(kind)}) l ${formatThemeColorNumber(C, 4)} ${formatThemeColorNumber(h, 2)})`;
688 +}
689 +
690 const CONTEXT_CHIP_CONTRAST = 5;
691 const CONTEXT_CHIP_MESSAGE_VARIABLE = "--context-chip-message";
692 const CONTEXT_CHIP_INVALID_VARIABLE = "--context-chip-invalid";
docs/user/composer.md
+4
@@ -353,6 +353,10 @@ saved text context at the time of the drop; later messages and the contents of a
353 are not copied. The agent can read the saved transcript after the source disconnects. Normal
354 file attachment limits apply.
355
356 +Type `@` and part of a model or provider name, such as `@opus`, to name that model for the
357 +agent, for example when delegating. It does not change the thread's model. Join words with
358 +`:`, `/` or `-`, as in `@opus:opencode`.
359 +
360 Images keep their thumbnail shelf above the text and also get a chip at your cursor, so you can
361 say exactly which image you mean. Deleting an image chip leaves the image on the shelf; removing
362 the thumbnail asks first when the image is still mentioned in your text, then removes both. Files
packages/client-runtime/package.json
+8
@@ -23,6 +23,14 @@
23 "types": "./src/composerThreadItems.ts",
24 "default": "./src/composerThreadItems.ts"
25 },
26 + "./composer-model-mentions": {
27 + "types": "./src/composerModelMentions.ts",
28 + "default": "./src/composerModelMentions.ts"
29 + },
30 + "./model-search": {
31 + "types": "./src/modelSearch.ts",
32 + "default": "./src/modelSearch.ts"
33 + },
34 "./image-attachment-size": {
35 "types": "./src/imageAttachmentSize.ts",
36 "default": "./src/imageAttachmentSize.ts"
packages/client-runtime/src/composerModelMentions.test.ts new
+100
@@ -0,0 +1,100 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import {
4 + collectComposerModelMentions,
5 + formatComposerModelMention,
6 + rankComposerModelMentions,
7 +} from "./composerModelMentions.ts";
8 +
9 +const models = [
10 + { id: "traex:gpt", name: "GPT-6.1", driverKind: "codex", providerDisplayName: "Traex" },
11 + {
12 + id: "opencode:traex-gpt",
13 + name: "GPT-6.1",
14 + subProvider: "Traex",
15 + driverKind: "opencode",
16 + providerDisplayName: "OpenCode",
17 + },
18 + {
19 + id: "opencode:opus",
20 + name: "Claude Opus 5.5",
21 + subProvider: "Anthropic",
22 + driverKind: "opencode",
23 + providerDisplayName: "OpenCode",
24 + },
25 + {
26 + id: "claude:opus",
27 + name: "Claude Opus 5.5",
28 + driverKind: "claudeAgent",
29 + providerDisplayName: "Claude",
30 + },
31 +];
32 +
33 +function rank(query: string): string[] {
34 + return rankComposerModelMentions(models, query, (model) => model).map((model) => model.id);
35 +}
36 +
37 +describe("rankComposerModelMentions", () => {
38 + it.each(["", "-", "---", ":/-/:"])(
39 + "offers no models for a bare or separator-only @%s",
40 + (query) => {
41 + expect(rank(query)).toEqual([]);
42 + },
43 + );
44 +
45 + it("finds a model under every provider that serves it", () => {
46 + expect(rank("gpt").toSorted()).toEqual(["opencode:traex-gpt", "traex:gpt"]);
47 + });
48 +
49 + it("splits words a mention joins with :, / or -", () => {
50 + expect(rank("opencode:traex")).toEqual(["opencode:traex-gpt"]);
51 + expect(rank("opencode/gpt")).toEqual(["opencode:traex-gpt"]);
52 + expect(rank("opencode-gpt")).toEqual(["opencode:traex-gpt"]);
53 + });
54 +
55 + it("keeps a hyphenated model name whole when it matches", () => {
56 + expect(rank("gpt-6.1").toSorted()).toEqual(["opencode:traex-gpt", "traex:gpt"]);
57 + });
58 +
59 + it.each(["src", "g", "agent", "pus"])(
60 + "does not offer models whose words only contain @%s",
61 + (query) => {
62 + expect(rank(query)).toEqual([]);
63 + },
64 + );
65 +});
66 +
67 +describe("collectComposerModelMentions", () => {
68 + it("reads back what formatComposerModelMention writes, inside prose", () => {
69 + const text = `use ${formatComposerModelMention("opencode", "anthropic/opus")}, then model:codex/gpt-5.4.`;
70 + expect(collectComposerModelMentions(text)).toEqual([
71 + {
72 + instanceId: "opencode",
73 + model: "anthropic/opus",
74 + source: "model:opencode/anthropic/opus",
75 + start: 4,
76 + end: 33,
77 + },
78 + { instanceId: "codex", model: "gpt-5.4", source: "model:codex/gpt-5.4", start: 40, end: 59 },
79 + ]);
80 + });
81 +
82 + it.each([
83 + ["(model:codex/gpt-6.1).", ["codex/gpt-6.1"]],
84 + ['"model:codex/gpt-6.1"', ["codex/gpt-6.1"]],
85 + ["model:codex/gpt-6.1,model:claudeAgent/sonnet", ["codex/gpt-6.1", "claudeAgent/sonnet"]],
86 + ["model:codex/gpt-6.1's output", ["codex/gpt-6.1"]],
87 + ["model:opencode/foo(bar)", ["opencode/foo(bar)"]],
88 + ])("bounds the reference in %s", (text, expected) => {
89 + expect(
90 + collectComposerModelMentions(text).map(({ instanceId, model }) => `${instanceId}/${model}`),
91 + ).toEqual(expected);
92 + });
93 +
94 + it.each(["remodel:codex/gpt", "model:codex", "model:/gpt", "model:codex/.", "model:1x/gpt"])(
95 + "ignores %s",
96 + (text) => {
97 + expect(collectComposerModelMentions(text)).toEqual([]);
98 + },
99 + );
100 +});
packages/client-runtime/src/composerModelMentions.ts new
+97
@@ -0,0 +1,97 @@
1 +import { rankModelPickerSearch, type ModelPickerSearchableModel } from "./modelSearch.ts";
2 +
3 +const COMPOSER_MODEL_MENTION_LIMIT = 8;
4 +
5 +const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
6 +
7 +/** Mentions can't contain spaces, so `:`, `/` and `-` split words, as in `@gpt:traex`. */
8 +function mentionSearchQueries(query: string): ReadonlyArray<string> {
9 + const spaced = query.replace(/[:/]+/gu, " ").trim();
10 + const unhyphenated = spaced.replace(/-+/gu, " ").trim();
11 + // One letter would fill the menu with models and push files out of it.
12 + if (unhyphenated.replace(/\s+/gu, "").length < 2) return [];
13 + return unhyphenated === spaced ? [spaced] : [spaced, unhyphenated];
14 +}
15 +
16 +/** Returns the models matching an `@` mention, best first. A bare `@` matches none. */
17 +export function rankComposerModelMentions<T>(
18 + candidates: ReadonlyArray<T>,
19 + query: string,
20 + toSearchable: (candidate: T) => ModelPickerSearchableModel,
21 +): T[] {
22 + for (const words of mentionSearchQueries(query)) {
23 + // Every word must start a word of the model's names. Fuzzy hits would push files out of the `@` menu.
24 + const tokens = words
25 + .toLowerCase()
26 + .split(/\s+/u)
27 + .map((token) => new RegExp(`(?:^|[^\\p{L}\\p{N}])${escapeRegExp(token)}`, "u"));
28 + const literal = candidates.filter((candidate) => {
29 + const model = toSearchable(candidate);
30 + const haystack = [
31 + model.name,
32 + model.shortName,
33 + model.subProvider,
34 + model.driverKind,
35 + model.providerDisplayName,
36 + ]
37 + .join(" ")
38 + .toLowerCase();
39 + return tokens.every((token) => token.test(haystack));
40 + });
41 + const ranked = rankModelPickerSearch(literal, words, toSearchable);
42 + if (ranked.length > 0) return ranked.slice(0, COMPOSER_MODEL_MENTION_LIMIT);
43 + }
44 + return [];
45 +}
46 +
47 +/** Prompt text naming a provider instance and model for the agent. No `@`, which the editor would turn into a file chip. */
48 +export function formatComposerModelMention(instanceId: string, model: string): string {
49 + return `model:${instanceId}/${model}`;
50 +}
51 +
52 +export interface ComposerModelMentionOccurrence {
53 + readonly instanceId: string;
54 + readonly model: string;
55 + readonly source: string;
56 + readonly start: number;
57 + readonly end: number;
58 +}
59 +
60 +// Instance ids match ProviderInstanceId; model slugs may contain `/`, as in `opencode/anthropic/opus`.
61 +const MODEL_MENTION_PATTERN = /(?<![^\s,(["'])model:([a-zA-Z][a-zA-Z0-9_-]*)\/([^\s,"']+)/gu;
62 +const SENTENCE_PUNCTUATION = ".;:!?";
63 +const CLOSING_BRACKETS: Readonly<Record<string, string>> = { ")": "(", "]": "[" };
64 +
65 +function countOf(text: string, char: string): number {
66 + return text.split(char).length - 1;
67 +}
68 +
69 +// Slugs like `foo(bar)` or `GPT-6.1-Sol[1m]` keep balanced brackets; prose wrapping them does not.
70 +function trimModelSlug(slug: string): string {
71 + let trimmed = slug;
72 + while (trimmed.length > 0) {
73 + const last = trimmed.at(-1)!;
74 + const opening = CLOSING_BRACKETS[last];
75 + const unbalanced = opening !== undefined && countOf(trimmed, opening) < countOf(trimmed, last);
76 + if (!SENTENCE_PUNCTUATION.includes(last) && !unbalanced) break;
77 + trimmed = trimmed.slice(0, -1);
78 + }
79 + return trimmed;
80 +}
81 +
82 +/** Finds the `model:<instance>/<model>` references that `formatComposerModelMention` writes. */
83 +export function collectComposerModelMentions(
84 + text: string,
85 +): ReadonlyArray<ComposerModelMentionOccurrence> {
86 + if (!text.includes("model:")) return [];
87 + const occurrences: ComposerModelMentionOccurrence[] = [];
88 + for (const match of text.matchAll(MODEL_MENTION_PATTERN)) {
89 + const instanceId = match[1]!;
90 + const model = trimModelSlug(match[2]!);
91 + if (model.length === 0) continue;
92 + const start = match.index;
93 + const end = start + "model:".length + instanceId.length + 1 + model.length;
94 + occurrences.push({ instanceId, model, source: text.slice(start, end), start, end });
95 + }
96 + return occurrences;
97 +}
packages/client-runtime/src/modelSearch.test.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { rankModelPickerSearch, scoreModelPickerSearch } from "./modelPickerSearch";
3 +import { rankModelPickerSearch, scoreModelPickerSearch } from "./modelSearch.ts";
4
5 describe("scoreModelPickerSearch", () => {
6 it("ranks exact token matches ahead of fuzzier matches", () => {
packages/client-runtime/src/modelSearch.ts renamed
+2 -2
@@ -1,6 +1,6 @@
1 import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";
2
3 -type ModelPickerSearchableModel = {
3 +export type ModelPickerSearchableModel = {
4 driverKind: string;
5 providerDisplayName: string;
6 name: string;
@@ -118,7 +118,7 @@ export function rankModelPickerSearch<T>(
118 }
119 });
120 return ranked
121 - .toSorted(
121 + .sort(
122 (a, b) =>
123 a.score - b.score || Number(b.isFavorite) - Number(a.isFavorite) || a.order - b.order,
124 )
packages/client-runtime/src/operations/threadTitle.test.ts new
+14
@@ -0,0 +1,14 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { threadTitleTextFromPrompt } from "./threadTitle.ts";
4 +
5 +describe("threadTitleTextFromPrompt", () => {
6 + it("names a mentioned model by its slug, without the reference syntax", () => {
7 + expect(threadTitleTextFromPrompt("Delegate to model:codex/gpt-6.1-sol and report back")).toBe(
8 + "Delegate to gpt-6.1-sol and report back",
9 + );
10 + expect(
11 + threadTitleTextFromPrompt("model:opencode/anthropic/opus, then model:codex/gpt-5.4."),
12 + ).toBe("anthropic/opus, then gpt-5.4.");
13 + });
14 +});
packages/client-runtime/src/operations/threadTitle.ts
+13 -1
@@ -3,6 +3,8 @@ import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitation
3 import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
4 import { truncate } from "@t3tools/shared/String";
5
6 +import { collectComposerModelMentions } from "../composerModelMentions.ts";
7 +
8 export interface ThreadTitleSeedInput {
9 readonly text: string;
10 readonly attachments: ReadonlyArray<Pick<ChatAttachment, "type" | "name">>;
@@ -13,6 +15,16 @@ function normalizeTitleSeed(value: string): string {
15 return assistantCitationsToPlainText(value).trim().replace(/\s+/gu, " ");
16 }
17
18 +function modelMentionsAsSlugs(value: string): string {
19 + let result = "";
20 + let cursor = 0;
21 + for (const mention of collectComposerModelMentions(value)) {
22 + result += value.slice(cursor, mention.start) + mention.model;
23 + cursor = mention.end;
24 + }
25 + return result + value.slice(cursor);
26 +}
27 +
28 export function threadTitleTextFromPrompt(value: string): string {
29 const imageIds = new Set<string>();
30 const prose = replaceComposerContextReferences(value, (reference) => {
@@ -23,7 +35,7 @@ export function threadTitleTextFromPrompt(value: string): string {
35 return reference.label;
36 });
37 return (
26 - normalizeTitleSeed(prose) ||
38 + normalizeTitleSeed(modelMentionsAsSlugs(prose)) ||
39 (imageIds.size > 0 ? (imageIds.size === 1 ? "Attached image" : "Attached images") : "")
40 );
41 }