The best way to control Claude Code, Codex and more from any computer or phone
fix(composer): only chip skills offered by the current provider (#14834)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Tristan Knight committed
Oct 20, 2026 at 03:20 UTC
4883320941f4ae5dac097a9c2eb95098f44fc753
10 files changed
+559
-250
apps/mobile/src/lib/composerContext.test.ts
+61
-3
@@ -7,6 +7,7 @@ import {
7
EnvironmentId,
8
ThreadId,
9
type OrchestrationMessageContext,
10
+ type ServerProviderSkill,
11
} from "@t3tools/contracts";
12
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
13
import {
@@ -18,6 +19,7 @@ import {
19
import { describe, expect, it } from "vite-plus/test";
20
import {
21
composerContextEditorTokens,
22
+ composerSkillLabels,
23
composerContextSendBlockReason,
24
composerMentionPath,
25
createComposerContextHistory,
@@ -162,10 +164,66 @@ describe("mobile composer context", () => {
164
});
165
it("keeps exact source positions and repeated references alongside existing native tokens", () => {
166
const reference = formatComposerContextReference(terminal);
165
- const text = `Use $playwright and [app.ts](src/app.ts) with ${reference} then ${reference}`;
166
- const tokens = composerContextEditorTokens(text, collectComposerInlineTokens(text));
167
- expect(tokens.map((token) => token.type)).toEqual(["skill", "mention", "context", "context"]);
167
+ const text = `Use $babysit with $disabled $agentOnly $HOME $PATH $anything $notaskill $20 $20k and [app.ts](src/app.ts) with ${reference} then ${reference}`;
168
+ const babysit: ServerProviderSkill = {
169
+ name: "babysit",
170
+ path: "/skills/babysit",
171
+ enabled: true,
172
+ };
173
+ const disabled = { ...babysit, name: "disabled", enabled: false };
174
+ const agentOnly = { ...babysit, name: "agentOnly", userInvocable: false };
175
+ const skills = [babysit, disabled, agentOnly];
176
+ const tokens = composerContextEditorTokens(
177
+ text,
178
+ collectComposerInlineTokens(text),
179
+ composerSkillLabels(skills),
180
+ );
181
+ expect(tokens.map((token) => token.source)).toEqual([
182
+ "$babysit",
183
+ "[app.ts](src/app.ts)",
184
+ reference,
185
+ reference,
186
+ ]);
187
for (const token of tokens) expect(text.slice(token.start, token.end)).toBe(token.source);
188
+ expect(
189
+ composerContextEditorTokens(
190
+ text,
191
+ collectComposerInlineTokens(text),
192
+ composerSkillLabels([]),
193
+ ).map((token) => token.type),
194
+ ).toEqual(["mention", "context", "context"]);
195
+ expect(
196
+ composerContextEditorTokens(
197
+ text,
198
+ collectComposerInlineTokens(text),
199
+ composerSkillLabels([{ ...babysit, name: "HOME" }]),
200
+ )
201
+ .filter((token) => token.type === "skill")
202
+ .map((token) => token.source),
203
+ ).toEqual(["$HOME"]);
204
+ const promoted = [
205
+ babysit,
206
+ { ...disabled, enabled: true },
207
+ { ...agentOnly, userInvocable: true },
208
+ ];
209
+ expect(
210
+ composerContextEditorTokens(
211
+ text,
212
+ collectComposerInlineTokens(text),
213
+ composerSkillLabels(promoted),
214
+ )
215
+ .filter((token) => token.type === "skill")
216
+ .map((token) => token.source),
217
+ ).toEqual(["$babysit", "$disabled", "$agentOnly"]);
218
+ expect(
219
+ composerContextEditorTokens(
220
+ text,
221
+ collectComposerInlineTokens(text),
222
+ composerSkillLabels(skills),
223
+ )
224
+ .filter((token) => token.type === "skill")
225
+ .map((token) => token.source),
226
+ ).toEqual(["$babysit"]);
227
});
228
229
it("removes deleted payloads but keeps the screenshot linked to a remaining annotation", () => {
apps/mobile/src/lib/composerContext.ts
+23
-2
@@ -1,3 +1,4 @@
1
+import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
2
import { serializeLegacyContextMessage } from "@t3tools/shared/composerContextLegacySend";
3
import { filePreviewKind } from "@t3tools/shared/filePreview";
4
import { videoMimeType } from "@t3tools/shared/video";
@@ -10,6 +11,7 @@ import {
11
type PullRequestContextMetadata,
12
type ReviewCommentContextRecord,
13
type ScopedThreadRef,
14
+ type ServerProviderSkill,
15
type ThreadContextRecord,
16
} from "@t3tools/contracts";
17
import * as Schema from "effect/Schema";
@@ -147,11 +149,30 @@ export function pullRequestComposerContext(
149
};
150
}
151
150
-export function composerContextEditorTokens(text: string, tokens: readonly ComposerInlineToken[]) {
152
+export function composerSkillLabels(
153
+ skills: ReadonlyArray<
154
+ Pick<ServerProviderSkill, "name" | "displayName" | "enabled" | "userInvocable">
155
+ >,
156
+) {
157
+ return new Map(
158
+ skills
159
+ .filter(isProviderSkillUserInvocable)
160
+ .map((skill) => [skill.name, skill.displayName?.trim() || skill.name]),
161
+ );
162
+}
163
+
164
+export function composerContextEditorTokens(
165
+ text: string,
166
+ tokens: readonly ComposerInlineToken[],
167
+ knownSkills: { has(name: string): boolean },
168
+) {
169
const references = collectComposerContextReferences(text);
170
return [
171
...tokens.filter(
154
- (token) => !references.some((ref) => token.start < ref.end && token.end > ref.start),
172
+ (token) =>
173
+ // `$HOME` and other `$name` text that is not one of the provider's skills stays prose.
174
+ (token.type !== "skill" || knownSkills.has(token.value)) &&
175
+ !references.some((ref) => token.start < ref.end && token.end > ref.start),
176
),
177
...references.map((ref) => ({
178
type: "context" as const,
apps/mobile/src/native/T3ComposerEditor.ios.tsx
+3
-6
@@ -1,7 +1,7 @@
1
import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
2
import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
3
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4
-import { composerContextEditorTokens } from "../lib/composerContext";
4
+import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
5
import { requireNativeView } from "expo";
6
import {
7
useCallback,
@@ -152,17 +152,14 @@ export function ComposerEditor({
152
[],
153
);
154
155
- const skillLabels = useMemo(
156
- () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
157
- [skills],
158
- );
155
+ const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
156
const tokensJson = useMemo(() => {
157
const tokens = collectComposerInlineTokens(props.value, {
158
preserveTrailingFrom: confirmedTokensRef.current,
159
});
160
confirmedTokensRef.current = tokens;
161
return JSON.stringify(
165
- composerContextEditorTokens(props.value, tokens).map((token) => {
162
+ composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
163
const record =
164
token.type === "context"
165
? props.context?.records.find((record) => record.contextId === token.contextId)
apps/mobile/src/native/T3ComposerEditor.native.tsx
+3
-6
@@ -1,7 +1,7 @@
1
import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
2
import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
3
import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4
-import { composerContextEditorTokens } from "../lib/composerContext";
4
+import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
5
import { requireNativeView } from "expo";
6
import { TextInputWrapper } from "expo-paste-input";
7
import {
@@ -150,17 +150,14 @@ export function ComposerEditor({
150
[],
151
);
152
153
- const skillLabels = useMemo(
154
- () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
155
- [skills],
156
- );
153
+ const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
154
const tokensJson = useMemo(() => {
155
const tokens = collectComposerInlineTokens(props.value, {
156
preserveTrailingFrom: confirmedTokensRef.current,
157
});
158
confirmedTokensRef.current = tokens;
159
return JSON.stringify(
163
- composerContextEditorTokens(props.value, tokens).map((token) => {
160
+ composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
161
const record =
162
token.type === "context"
163
? props.context?.records.find((record) => record.contextId === token.contextId)
apps/mobile/src/native/T3ComposerEditor.types.ts
+4
-1
@@ -36,7 +36,10 @@ export interface ComposerEditorProps {
36
},
37
) => void;
38
readonly skills?: ReadonlyArray<
39
- Pick<ServerProviderSkill, "name" | "displayName" | "shortDescription" | "description"> &
39
+ Pick<
40
+ ServerProviderSkill,
41
+ "name" | "displayName" | "shortDescription" | "description" | "enabled" | "userInvocable"
42
+ > &
43
Partial<Pick<ServerProviderSkill, "path">>
44
>;
45
readonly selection?: ComposerEditorSelection;
apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+194
-12
@@ -1,10 +1,16 @@
1
+import type { ServerProviderSkill } from "@t3tools/contracts";
2
import type { Editor } from "@tiptap/core";
2
-import { act, createRef } from "react";
3
+import { act, createRef, useState } from "react";
4
import { createRoot, type Root } from "react-dom/client";
5
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6
7
+import { detectComposerTrigger } from "~/composer-logic";
8
import { serializeEditorDoc } from "~/composer-rich-text-doc";
7
-import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
9
+import {
10
+ ComposerPromptEditor,
11
+ type ComposerPromptEditorHandle,
12
+ type ComposerPromptEditorProps,
13
+} from "./ComposerPromptEditor";
14
15
let root: Root;
16
let container: HTMLDivElement;
@@ -22,20 +28,56 @@ afterEach(async () => {
28
vi.unstubAllGlobals();
29
});
30
25
-async function mountEditor(value: string, richTextEnabled = true) {
31
+const babysit: ServerProviderSkill = {
32
+ name: "babysit",
33
+ path: "/skills/babysit/SKILL.md",
34
+ enabled: true,
35
+};
36
+
37
+function Composer({
38
+ value,
39
+ richTextEnabled,
40
+ skills,
41
+ onChange,
42
+}: {
43
+ value: string;
44
+ richTextEnabled: boolean;
45
+ skills: ReadonlyArray<ServerProviderSkill>;
46
+ onChange?: ComposerPromptEditorProps["onChange"] | undefined;
47
+}) {
48
+ const [prompt, setPrompt] = useState({ value, cursor: value.length });
49
+ return (
50
+ <ComposerPromptEditor
51
+ editorRef={createRef<ComposerPromptEditorHandle>()}
52
+ value={prompt.value}
53
+ cursor={prompt.cursor}
54
+ richTextEnabled={richTextEnabled}
55
+ contextRecords={new Map()}
56
+ skills={skills}
57
+ disabled={false}
58
+ placeholder=""
59
+ onChange={(...args) => {
60
+ setPrompt({ value: args[0], cursor: args[1] });
61
+ onChange?.(...args);
62
+ }}
63
+ onPaste={() => {}}
64
+ />
65
+ );
66
+}
67
+
68
+async function mountEditor(
69
+ value: string,
70
+ richTextEnabled = true,
71
+ skills: ReadonlyArray<ServerProviderSkill> = [],
72
+ onChange?: ComposerPromptEditorProps["onChange"],
73
+) {
74
await act(async () =>
75
root.render(
28
- <ComposerPromptEditor
29
- editorRef={createRef<ComposerPromptEditorHandle>()}
76
+ <Composer
77
value={value}
31
- cursor={value.length}
78
richTextEnabled={richTextEnabled}
33
- contextRecords={new Map()}
34
- skills={[]}
35
- disabled={false}
36
- placeholder=""
37
- onChange={() => {}}
38
- onPaste={() => {}}
79
+ skills={skills}
80
+ onChange={onChange}
81
/>,
82
),
83
);
@@ -135,3 +177,143 @@ it.each([false, true])(
177
expect(serializeEditorDoc(editor.state.doc).value).toBe('"word"');
178
},
179
);
180
+
181
+it("keeps unknown dollar names editable when restoring and pasting a draft", async () => {
182
+ const value = "echo $HOME $PATH $anything $notaskill $20 $20k $babysit ";
183
+ const editor = await mountEditor(value, true, [babysit]);
184
+ expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
185
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
186
+ await act(async () => {
187
+ editor.commands.setTextSelection("echo $HO".length + 1);
188
+ editor.commands.insertContent("X");
189
+ });
190
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value.replace("$HOME", "$HOXME"));
191
+ await act(async () => {
192
+ editor.commands.selectAll();
193
+ const clipboardData = new DataTransfer();
194
+ clipboardData.setData("text/plain", value);
195
+ editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
196
+ });
197
+ expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
198
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
199
+});
200
+
201
+it("keeps skill queries active before whitespace and line breaks, suppressing only real chips", async () => {
202
+ const onChange = vi.fn<ComposerPromptEditorProps["onChange"]>();
203
+ const editor = await mountEditor("use now\nfirst \n$babysit tail", true, [babysit], onChange);
204
+ const trigger = () => {
205
+ const [value, , expandedCursor, suppressTrigger] = onChange.mock.lastCall!;
206
+ return suppressTrigger ? null : detectComposerTrigger(value, expandedCursor);
207
+ };
208
+ await act(async () => {
209
+ editor.commands.setTextSelection("use ".length + 1);
210
+ typeText(editor, editor.state.selection.from, editor.state.selection.to, "$bab");
211
+ });
212
+ expect.soft(trigger()).toMatchObject({ kind: "skill", query: "bab" });
213
+ await act(async () => {
214
+ editor.commands.setTextSelection(editor.state.doc.child(0).nodeSize + 1 + "first ".length);
215
+ typeText(editor, editor.state.selection.from, editor.state.selection.to, "$bab");
216
+ });
217
+ expect.soft(trigger()).toMatchObject({ kind: "skill", query: "bab" });
218
+ await act(async () => {
219
+ editor.commands.setHardBreak();
220
+ });
221
+ await act(async () => {
222
+ editor.commands.setTextSelection(editor.state.selection.from - 1);
223
+ });
224
+ expect(editor.state.selection.$from.nodeAfter?.type.name).toBe("hardBreak");
225
+ expect.soft(trigger()).toMatchObject({ kind: "skill", query: "bab" });
226
+
227
+ const chip = serializeEditorDoc(editor.state.doc).runs.find((run) => run.kind === "token")!;
228
+ await act(async () => {
229
+ editor.commands.setTextSelection(chip.pmPos);
230
+ });
231
+ expect(onChange.mock.lastCall![3]).toBe(true);
232
+ await act(async () => {
233
+ editor.commands.setTextSelection(chip.pmPos + 1);
234
+ });
235
+ expect(onChange.mock.lastCall![3]).toBe(true);
236
+ expect(trigger()).toBeNull();
237
+});
238
+
239
+it("keeps the caret inside unknown dollar text across rich and plain remounts", async () => {
240
+ const value = "echo $HOME now";
241
+ let editor = await mountEditor(value);
242
+ await act(async () => {
243
+ editor.commands.setTextSelection("echo $HO".length + 1);
244
+ });
245
+ editor = await mountEditor(value, false);
246
+ await act(async () => {
247
+ editor.commands.insertContent("X");
248
+ });
249
+ expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXME now");
250
+ editor = await mountEditor(value, true);
251
+ await act(async () => {
252
+ editor.commands.insertContent("Y");
253
+ });
254
+ expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXYME now");
255
+});
256
+
257
+it("reconciles provider skills and metadata without losing formatting, caret, or undo", async () => {
258
+ const value = "run **use $babysit now** then $HOME";
259
+ const disabled = { ...babysit, enabled: false };
260
+ const agentOnly = { ...babysit, userInvocable: false };
261
+ const editor = await mountEditor(value, true, [disabled]);
262
+ expect.soft(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
263
+ await mountEditor(value, true, [agentOnly]);
264
+ expect.soft(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
265
+ await act(async () => {
266
+ editor.commands.setTextSelection("run use $baby".length + 1);
267
+ });
268
+ await mountEditor(value, true, [disabled, babysit]);
269
+ expect(editor.state.doc.textContent).toBe("run use now then $HOME");
270
+ const chip = serializeEditorDoc(editor.state.doc).runs.find((run) => run.kind === "token")!;
271
+ expect(editor.state.selection.from).toBe(chip.pmPos + 1);
272
+ await mountEditor(value, true, [disabled]);
273
+ expect.soft(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
274
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
275
+ await act(async () => {
276
+ editor.commands.insertContent("X");
277
+ });
278
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value.replace("$babysit", "$babysitX"));
279
+ await act(async () => {
280
+ editor.commands.undo();
281
+ });
282
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
283
+ expect(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
284
+
285
+ await mountEditor(value, true, [babysit]);
286
+ await act(async () => {
287
+ editor.commands.deleteRange({ from: chip.pmPos, to: chip.pmPos + 1 });
288
+ });
289
+ await mountEditor(value, true, [agentOnly]);
290
+ await act(async () => {
291
+ editor.commands.undo();
292
+ });
293
+ expect(editor.state.doc.textContent).toBe("run use $babysit now then $HOME");
294
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
295
+
296
+ await mountEditor(value, true, [{ ...babysit, description: "Previous provider description" }]);
297
+ await act(async () => {
298
+ container
299
+ .querySelector<HTMLButtonElement>('[aria-label="Skill Babysit. Show details"]')!
300
+ .click();
301
+ });
302
+ expect(document.body.textContent).toContain("Previous provider description");
303
+ await mountEditor(value, true, [
304
+ { ...disabled, displayName: "Disabled Babysit" },
305
+ {
306
+ ...babysit,
307
+ displayName: "Current Babysit",
308
+ shortDescription: " Current short description ",
309
+ },
310
+ ]);
311
+ expect(container.textContent).toContain("Current Babysit");
312
+ expect(document.body.textContent).toContain("Current short description");
313
+ expect(document.body.textContent).not.toContain("Previous provider description");
314
+ await mountEditor(value, true, [{ ...babysit, displayName: "Current Babysit" }]);
315
+ expect(container.textContent).toContain("Current Babysit");
316
+ expect(document.body.textContent).not.toContain("Current short description");
317
+ expect(document.body.textContent).toContain("No description is available for this skill.");
318
+ expect(document.body.textContent).not.toContain("Previous provider description");
319
+});
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+120
-68
@@ -1,3 +1,4 @@
1
+import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
2
import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
3
import {
4
Extension,
@@ -11,6 +12,7 @@ import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tip
12
import StarterKit from "@tiptap/starter-kit";
13
import { type Node as ProseMirrorNode } from "@tiptap/pm/model";
14
import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands";
15
+import { isHistoryTransaction } from "@tiptap/pm/history";
16
import {
17
type EditorState,
18
NodeSelection,
@@ -50,7 +52,6 @@ import {
52
clampCollapsedComposerCursor,
53
collapseExpandedComposerCursor,
54
expandCollapsedComposerCursor,
53
- isCollapsedCursorAdjacentToInlineToken,
55
pastedPathQueryLength,
56
} from "~/composer-logic";
57
import { useStableCallback } from "~/hooks/useStableCallback";
@@ -64,18 +65,18 @@ import {
65
ComposerCodeBlockExtension,
66
ComposerListExtensions,
67
buildTiptapContent,
67
- collapsedToFlat,
68
caretTakesMarksBefore,
69
convertBulletItemToTask,
70
ComposerCodeExtension,
71
ComposerTaskItemExtension,
72
ComposerTaskListExtension,
73
- flatToCollapsed,
73
flatToMarkdown,
74
flatToPm,
75
+ markdownToFlat,
76
pmToFlat,
77
serializeEditorDoc,
78
serializeSelection,
79
+ skillChipReplacements,
80
splitOrLiftListItem,
81
stepCaretAcrossStyledEdge,
82
type SkillMeta,
@@ -316,13 +317,37 @@ const ComposerSkillExtension = Node.create({
317
},
318
});
319
320
+/** Chip presentation for `$name`, or null when the provider does not offer it to users. */
321
+function composerSkillMeta(
322
+ skills: ReadonlyArray<ServerProviderSkill>,
323
+ name: string,
324
+): SkillMeta | null {
325
+ const skill = skills.find(
326
+ (candidate) => candidate.name === name && isProviderSkillUserInvocable(candidate),
327
+ );
328
+ if (!skill) return null;
329
+ const shortDescription = skill.shortDescription?.trim();
330
+ return {
331
+ label: formatProviderSkillDisplayName(skill),
332
+ description: shortDescription || skill.description?.trim() || null,
333
+ };
334
+}
335
+
336
function ComposerSkillNodeView({ node }: NodeViewProps) {
337
const actions = use(ComposerContextActionsContext);
338
const skills = use(RichComposerSkillsContext);
339
const skillName = (node.attrs.skillName as string) ?? "";
323
- const skillLabel = (node.attrs.skillLabel as string) || skillName;
340
const skillDescription = (node.attrs.skillDescription as string | null) ?? null;
325
- const skill = skills.find((candidate) => candidate.name === skillName);
341
+ const skill = skills.find(
342
+ (candidate) => candidate.name === skillName && isProviderSkillUserInvocable(candidate),
343
+ );
344
+ const description = skill
345
+ ? skill.description?.trim() || skill.shortDescription?.trim()
346
+ : skillDescription;
347
+ // The node outlives a provider switch, so its stored label can be another provider's.
348
+ const skillLabel = skill
349
+ ? formatProviderSkillDisplayName(skill)
350
+ : (node.attrs.skillLabel as string) || skillName;
351
return (
352
<NodeViewWrapper as="span" className={CHIP_NODE_SELECTION_CLASS_NAME}>
353
<ContextChipPopover
@@ -333,12 +358,8 @@ function ComposerSkillNodeView({ node }: NodeViewProps) {
358
>
359
<div className="space-y-3 p-2 text-sm">
360
<p className="font-medium">{skillLabel}</p>
336
- <p>
337
- {skill?.description ??
338
- skillDescription ??
339
- "No description is available for this skill."}
340
- </p>
341
- {skill?.path ? (
361
+ <p>{description || "No description is available for this skill."}</p>
362
+ {skill?.path && actions.environmentId ? (
363
<Button variant="outline" size="sm" onClick={() => actions.openMention(skill.path)}>
364
View instructions
365
</Button>
@@ -743,12 +764,43 @@ const ComposerMarkersExtension = Extension.create({
764
765
type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;
766
767
+function replaceSkillChips(
768
+ editor: TiptapEditor,
769
+ replacements: ReturnType<typeof skillChipReplacements>,
770
+): void {
771
+ const transaction = editor.state.tr.setMeta("addToHistory", false);
772
+ for (const { from, to, node } of replacements) transaction.replaceWith(from, to, node);
773
+ editor.view.dispatch(transaction);
774
+}
775
+
776
export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) {
747
- // Extensions are creation-time, so changing text mode remounts the editor.
777
+ const { onChange: onPromptChange } = props;
778
+ const [selection, setSelection] = useState<{
779
+ value: string;
780
+ cursor: number;
781
+ expandedCursor: number;
782
+ } | null>(null);
783
+ const onChange: ComposerPromptEditorProps["onChange"] = (
784
+ value,
785
+ cursor,
786
+ expandedCursor,
787
+ ...rest
788
+ ) => {
789
+ setSelection({ value, cursor, expandedCursor });
790
+ onPromptChange(value, cursor, expandedCursor, ...rest);
791
+ };
792
+ // Changing text mode remounts the editor. Its collapsed cursor cannot represent
793
+ // a caret inside unknown `$name` text, so retain the exact Markdown offset here.
794
return (
795
<ComposerPromptEditorTiptapInner
796
key={props.literalText ? "literal" : props.richTextEnabled ? "rich" : "plain"}
797
{...props}
798
+ initialExpandedCursor={
799
+ selection?.value === props.value && selection.cursor === props.cursor
800
+ ? selection.expandedCursor
801
+ : expandCollapsedComposerCursor(props.value, props.cursor, props.literalText)
802
+ }
803
+ onChange={onChange}
804
/>
805
);
806
}
@@ -879,7 +931,9 @@ function createComposerExtensions(richText: boolean) {
931
const RICH_TEXT_EXTENSIONS = createComposerExtensions(true);
932
const PLAIN_TEXT_EXTENSIONS = createComposerExtensions(false);
933
882
-function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
934
+function ComposerPromptEditorTiptapInner(
935
+ props: ComposerPromptEditorProps & { initialExpandedCursor: number },
936
+) {
937
const {
938
value,
939
cursor,
@@ -952,21 +1006,10 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1006
}, [value]);
1007
1008
// Stable so a skills refresh does not rerun the controlled-value effect.
955
- const skillLabelFor = useStableCallback((name: string): SkillMeta => {
956
- const normalized = name.startsWith("$") ? name.slice(1) : name;
957
- const skill = skills.find((candidate) => candidate.name === normalized);
958
- if (!skill) {
959
- return { label: formatProviderSkillDisplayName({ name: normalized }), description: null };
960
- }
961
- const shortDescription = skill.shortDescription?.trim();
962
- return {
963
- label: formatProviderSkillDisplayName(skill),
964
- description: shortDescription || skill.description?.trim() || null,
965
- };
966
- });
1009
+ const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name));
1010
1011
const initialCursor = clampEditorCursor(value, cursor);
969
- const initialExpandedCursor = expandEditorCursor(value, initialCursor);
1012
+ const initialExpandedCursor = Math.max(0, Math.min(value.length, props.initialExpandedCursor));
1013
const snapshotRef = useRef({
1014
value,
1015
cursor: initialCursor,
@@ -1006,11 +1049,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1049
const fromFlat = pmToFlat(map, from);
1050
const toFlat = pmToFlat(map, to);
1051
const nextValue = map.value;
1009
- const nextCursor = clampEditorCursor(map.value, flatToCollapsed(map, fromFlat));
1052
const nextExpandedCursor = Math.max(
1053
0,
1054
Math.min(map.value.length, flatToMarkdown(map, fromFlat)),
1055
);
1056
+ const nextCursor = collapseExpandedComposerCursor(map.value, nextExpandedCursor, literalText);
1057
const nextSelectionRange = {
1058
start: Math.min(nextExpandedCursor, flatToMarkdown(map, toFlat)),
1059
end: Math.max(nextExpandedCursor, flatToMarkdown(map, toFlat)),
@@ -1049,8 +1092,9 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1092
const suppressTrigger =
1093
literalText ||
1094
inCodeBlock ||
1052
- isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
1053
- isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
1095
+ [updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some(
1096
+ (node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak",
1097
+ );
1098
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds);
1099
};
1100
@@ -1083,25 +1127,10 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1127
const editor = useEditor(
1128
{
1129
extensions: richText ? RICH_TEXT_EXTENSIONS : PLAIN_TEXT_EXTENSIONS,
1086
- content: buildDocJson(
1087
- value,
1088
- (name) => {
1089
- const normalized = name.startsWith("$") ? name.slice(1) : name;
1090
- const found = skills.find((candidate) => candidate.name === normalized);
1091
- if (!found) {
1092
- return {
1093
- label: formatProviderSkillDisplayName({ name: normalized }),
1094
- description: null,
1095
- };
1096
- }
1097
- const shortDescription = found.shortDescription?.trim();
1098
- return {
1099
- label: formatProviderSkillDisplayName(found),
1100
- description: shortDescription || found.description?.trim() || null,
1101
- };
1102
- },
1103
- { styling: richText, literalText },
1104
- ),
1130
+ content: buildDocJson(value, (name) => composerSkillMeta(skills, name), {
1131
+ styling: richText,
1132
+ literalText,
1133
+ }),
1134
editable: !disabled,
1135
editorProps: {
1136
attributes: editorAttributes,
@@ -1370,17 +1399,14 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1399
? importPastedComposerText(clipboardData, importFragment)
1400
: pastedText;
1401
const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`);
1402
+ const isChip = (token: (typeof tokens)[number] | undefined) =>
1403
+ token?.type === "mention" ||
1404
+ (token?.type === "skill" && skillLabelFor(token.value) !== null);
1405
const lastToken = tokens.at(-1);
1374
- if (
1375
- (lastToken?.type === "mention" || lastToken?.type === "skill") &&
1376
- lastToken.end === text.length
1377
- ) {
1406
+ if (isChip(lastToken) && lastToken?.end === text.length) {
1407
text += " ";
1408
}
1380
- if (
1381
- (tokens[0]?.type === "mention" || tokens[0]?.type === "skill") &&
1382
- tokens[0].start === 0
1383
- ) {
1409
+ if (isChip(tokens[0]) && tokens[0]?.start === 0) {
1410
const map = serializeEditorDoc(view.state.doc);
1411
const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from));
1412
if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`;
@@ -1430,7 +1456,17 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1456
return true;
1457
},
1458
},
1433
- onUpdate: ({ editor: updated }) => {
1459
+ onUpdate: ({ editor: updated, transaction }) => {
1460
+ // Undo can restore a chip for a skill the current provider no longer offers.
1461
+ if (!literalText && isHistoryTransaction(transaction)) {
1462
+ const stale = skillChipReplacements(updated.state.doc, skillLabelFor).filter(
1463
+ ({ node }) => node.isText,
1464
+ );
1465
+ if (stale.length > 0) {
1466
+ replaceSkillChips(updated, stale);
1467
+ return;
1468
+ }
1469
+ }
1470
handleEditorChange(updated);
1471
},
1472
onSelectionUpdate: ({ editor: updated }) => {
@@ -1465,10 +1501,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1501
const map = serializeEditorDoc(editor.state.doc);
1502
const { from, to } = editor.state.selection;
1503
const fromFlat = pmToFlat(map, from);
1504
+ const expandedCursor = Math.max(0, Math.min(map.value.length, flatToMarkdown(map, fromFlat)));
1505
const next: typeof snapshot = {
1506
value: map.value,
1470
- cursor: clampEditorCursor(map.value, flatToCollapsed(map, fromFlat)),
1471
- expandedCursor: Math.max(0, Math.min(map.value.length, flatToMarkdown(map, fromFlat))),
1507
+ cursor: collapseExpandedComposerCursor(map.value, expandedCursor, literalText),
1508
+ expandedCursor,
1509
contextIds: literalText ? [] : map.contextIds,
1510
};
1511
const toFlat = pmToFlat(map, to);
@@ -1526,7 +1563,9 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1563
) {
1564
return;
1565
}
1529
- const normalizedExpandedCursor = expandEditorCursor(value, normalizedCursor);
1566
+ const normalizedExpandedCursor = initialSelection
1567
+ ? initialExpandedCursor
1568
+ : expandEditorCursor(value, normalizedCursor);
1569
snapshotRef.current = {
1570
value,
1571
cursor: normalizedCursor,
@@ -1555,7 +1594,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1594
);
1595
}
1596
const map = serializeEditorDoc(editor.state.doc);
1558
- const flat = collapsedToFlat(map, normalizedCursor);
1597
+ const flat = markdownToFlat(map, normalizedExpandedCursor);
1598
editor.commands.setTextSelection(flatToPm(map, flat));
1599
if (isFocused) scrollTiptapCaretIntoView(editor);
1600
if (pendingCitation) {
@@ -1586,13 +1625,23 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1625
cursor,
1626
editor,
1627
expandEditorCursor,
1628
+ initialExpandedCursor,
1629
literalText,
1630
richText,
1631
skillLabelFor,
1632
value,
1633
]);
1634
1595
- const focusAt = (nextCursor: number) => {
1635
+ // Reconcile loaded or switched provider skills without rebuilding citation node views.
1636
+ useEffect(() => {
1637
+ if (!editor || literalText) return;
1638
+ const replacements = skillChipReplacements(editor.state.doc, (name) =>
1639
+ composerSkillMeta(skills, name),
1640
+ );
1641
+ if (replacements.length > 0) replaceSkillChips(editor, replacements);
1642
+ }, [editor, literalText, skills]);
1643
+
1644
+ const focusAt = (nextCursor: number, exactExpandedCursor?: number) => {
1645
if (!editor) return;
1646
// view.focus() writes the state selection to the DOM as it focuses. A
1647
// bare DOM focus leaves the native caret at the start until
@@ -1601,15 +1650,16 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1650
editor.view.focus();
1651
if (snapshotRef.current.value !== latestValueRef.current) return;
1652
const boundedCursor = clampEditorCursor(snapshotRef.current.value, nextCursor);
1653
+ const expandedCursor =
1654
+ exactExpandedCursor ?? expandEditorCursor(snapshotRef.current.value, boundedCursor);
1655
const map = serializeEditorDoc(editor.state.doc);
1605
- const flat = collapsedToFlat(map, boundedCursor);
1606
- editor.commands.setTextSelection(flatToPm(map, flat));
1656
+ editor.commands.setTextSelection(flatToPm(map, markdownToFlat(map, expandedCursor)));
1657
scrollTiptapCaretIntoView(editor);
1658
if (boundedCursor === snapshotRef.current.cursor) return;
1659
snapshotRef.current = {
1660
value: snapshotRef.current.value,
1661
cursor: boundedCursor,
1612
- expandedCursor: expandEditorCursor(snapshotRef.current.value, boundedCursor),
1662
+ expandedCursor,
1663
contextIds: snapshotRef.current.contextIds,
1664
};
1665
selectionRangeRef.current = {
@@ -1629,9 +1679,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1679
editorRef,
1680
() => ({
1681
focus: () => {
1632
- focusAt(snapshotRef.current.cursor);
1682
+ // The collapsed cursor cannot say where inside `$name` text a caret
1683
+ // sits, so restoring the caret passes along its exact offset.
1684
+ focusAt(snapshotRef.current.cursor, snapshotRef.current.expandedCursor);
1685
},
1634
- focusAt,
1686
+ focusAt: (cursor) => focusAt(cursor),
1687
focusAtEnd: () => {
1688
focusAt(
1689
literalText
@@ -1808,7 +1860,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
1860
*/
1861
function insertMarkdownParagraphs(
1862
value: string,
1811
- skillLabelFor: (name: string) => SkillMeta,
1863
+ skillLabelFor: (name: string) => SkillMeta | null,
1864
options: { styling: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number },
1865
insertContent: (content: JSONContent[] | JSONContent) => void,
1866
): void {
apps/web/src/components/settings/SettingsFontPreviews.tsx
+5
-2
@@ -1,3 +1,4 @@
1
+import type { ServerProviderSkill } from "@t3tools/contracts";
2
import { preloadPatchFile } from "@pierre/diffs/ssr";
3
import { useEffect, useRef, useState } from "react";
4
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "../ComposerPromptEditor";
@@ -9,7 +10,9 @@ import { resolveDiffThemeName, type DiffThemeName } from "../../lib/diffRenderin
10
import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
11
import { GhosttyTerminalSurface } from "~/terminal/ghostty/surface";
12
12
-const EMPTY_SKILLS: ReadonlyArray<never> = [];
13
+const PREVIEW_SKILLS: ReadonlyArray<ServerProviderSkill> = [
14
+ { name: "frontend-design", path: ".agents/skills/frontend-design/SKILL.md", enabled: true },
15
+];
16
17
const PROMPT_PREVIEW_TEXT =
18
"Use $frontend-design to fix the flaky test in " +
@@ -34,7 +37,7 @@ export function PromptFontPreview() {
37
value={prompt}
38
cursor={cursor}
39
contextRecords={EMPTY_COMPOSER_CONTEXT_RECORDS}
37
- skills={EMPTY_SKILLS}
40
+ skills={PREVIEW_SKILLS}
41
disabled={false}
42
placeholder={DISCONNECTED_COMPOSER_PLACEHOLDER}
43
className="max-h-42 min-h-14"
apps/web/src/composer-rich-text-doc.test.ts
+55
-50
@@ -6,7 +6,11 @@ import { EditorState, TextSelection } from "@tiptap/pm/state";
6
import { splitBlockKeepMarks } from "@tiptap/pm/commands";
7
import { describe, expect, it, onTestFinished } from "vite-plus/test";
8
9
-import { collapseExpandedComposerCursor, pastedPathQueryLength } from "./composer-logic";
9
+import {
10
+ collapseExpandedComposerCursor,
11
+ expandCollapsedComposerCursor,
12
+ pastedPathQueryLength,
13
+} from "./composer-logic";
14
15
import {
16
buildDocJson,
@@ -15,15 +19,15 @@ import {
19
ComposerBlockExtensions,
20
ComposerCodeBlockExtension,
21
ComposerListExtensions,
18
- collapsedToFlat,
22
ComposerCodeExtension,
23
ComposerTaskItemExtension,
21
- flatToCollapsed,
24
flatToMarkdown,
25
flatToPm,
26
+ markdownToFlat,
27
pmToFlat,
28
serializeEditorDoc,
29
serializeSelection,
30
+ skillChipReplacements,
31
stepCaretAcrossStyledEdge,
32
} from "./composer-rich-text-doc";
33
@@ -205,7 +209,9 @@ describe("literal editor answers", () => {
209
expect(serialized.contextIds).toEqual([]);
210
expect(serializeSelection(doc, 1, doc.content.size - 1)).toBe(value);
211
for (let offset = 0; offset <= value.length; offset += 1) {
208
- expect(flatToCollapsed(serialized, offset)).toBe(offset);
212
+ expect(collapseExpandedComposerCursor(value, flatToMarkdown(serialized, offset), true)).toBe(
213
+ offset,
214
+ );
215
}
216
});
217
@@ -301,7 +307,7 @@ describe("composer rich text document model", () => {
307
const position = flatToPm(map, flat);
308
expect(doc.resolve(position).parent.isTextblock).toBe(true);
309
expect(pmToFlat(map, position)).toBe(flat);
304
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
310
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
311
}
312
});
313
@@ -412,7 +418,7 @@ describe("composer rich text document model", () => {
418
expect(serializeEditorDoc(rebuilt).value).toBe(map.value);
419
for (let flat = 0; flat <= map.docLength; flat += 1) {
420
expect(pmToFlat(map, flatToPm(map, flat))).toBe(flat);
415
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
421
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
422
if (flat < map.docLength && !/\s/.test(doc.textContent[flat]!)) {
423
expect(rebuilt.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name)).toEqual(
424
doc.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name),
@@ -490,12 +496,12 @@ describe("composer rich text document model", () => {
496
});
497
498
it.each(["- one\n- two", "1. a\n - b\n2. c", "- **bold** @README.md tail", "-"])(
493
- "maps every document offset of the list %s through collapsed coordinates and back",
499
+ "maps every document offset of the list %s through markdown coordinates and back",
500
(value) => {
501
const map = roundTrip(value);
502
expect(map.value).toBe(value);
503
for (let flat = 0; flat <= map.docLength; flat += 1) {
498
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
504
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
505
}
506
},
507
);
@@ -503,11 +509,11 @@ describe("composer rich text document model", () => {
509
it("clamps offsets inside a list marker to the start of the item text", () => {
510
const value = "- item";
511
const map = roundTrip(value);
506
- for (let collapsed = 0; collapsed <= "- ".length; collapsed += 1) {
507
- expect(collapsedToFlat(map, collapsed)).toBe(0);
512
+ for (let markdown = 0; markdown <= "- ".length; markdown += 1) {
513
+ expect(markdownToFlat(map, markdown)).toBe(0);
514
}
509
- expect(collapsedToFlat(map, "- it".length)).toBe(2);
510
- expect(flatToCollapsed(map, 0)).toBe("- ".length);
515
+ expect(markdownToFlat(map, "- it".length)).toBe(2);
516
+ expect(flatToMarkdown(map, 0)).toBe("- ".length);
517
});
518
519
it.each([
@@ -577,13 +583,13 @@ describe("composer rich text document model", () => {
583
it("keeps every offset mapped through the blank line", () => {
584
const { doc, map } = serialize(quote("quoted"), paragraph("Comment"));
585
for (let flat = 0; flat <= map.docLength; flat += 1) {
580
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
586
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
587
}
588
// The caret on the end of the quote stays on it, and the blank line is
589
// not a place to type: it clamps to the start of the comment.
584
- expect(flatToCollapsed(map, "quoted".length)).toBe("> quoted".length);
585
- expect(collapsedToFlat(map, "> quoted\n".length)).toBe("quoted".length + 1);
586
- expect(flatToCollapsed(map, "quoted".length + 1)).toBe("> quoted\n\n".length);
590
+ expect(flatToMarkdown(map, "quoted".length)).toBe("> quoted".length);
591
+ expect(markdownToFlat(map, "> quoted\n".length)).toBe("quoted".length + 1);
592
+ expect(flatToMarkdown(map, "quoted".length + 1)).toBe("> quoted\n\n".length);
593
expect(flatToPm(map, "quoted".length + 1)).toBe(doc.child(0).nodeSize + 1);
594
});
595
});
@@ -729,12 +735,12 @@ describe("composer rich text document model", () => {
735
"# Heading text",
736
"## **b** @README.md",
737
])(
732
- "maps every document offset of the block %s through collapsed coordinates and back",
738
+ "maps every document offset of the block %s through markdown coordinates and back",
739
(value) => {
740
const map = roundTrip(value);
741
expect(map.value).toBe(value);
742
for (let flat = 0; flat <= map.docLength; flat += 1) {
737
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
743
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
744
}
745
},
746
);
@@ -745,10 +751,10 @@ describe("composer rich text document model", () => {
751
["# Heading", "# "],
752
] as const) {
753
const map = roundTrip(value);
748
- for (let collapsed = 0; collapsed <= prefix.length; collapsed += 1) {
749
- expect(collapsedToFlat(map, collapsed)).toBe(0);
754
+ for (let markdown = 0; markdown <= prefix.length; markdown += 1) {
755
+ expect(markdownToFlat(map, markdown)).toBe(0);
756
}
751
- expect(flatToCollapsed(map, 0)).toBe(prefix.length);
757
+ expect(flatToMarkdown(map, 0)).toBe(prefix.length);
758
}
759
});
760
@@ -774,12 +780,12 @@ describe("composer rich text document model", () => {
780
});
781
782
it.each(["```ts\nconst a = 1;\n```", "```\n```", "before\n```ts\ncode\n```\nafter"])(
777
- "maps every document offset of %s through collapsed coordinates and back",
783
+ "maps every document offset of %s through markdown coordinates and back",
784
(value) => {
785
const map = roundTrip(value);
786
expect(map.value).toBe(value);
787
for (let flat = 0; flat <= map.docLength; flat += 1) {
782
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
788
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
789
}
790
},
791
);
@@ -801,17 +807,16 @@ describe("composer rich text document model", () => {
807
const value = "```ts\nfunc();\n```";
808
const map = roundTrip(value);
809
const endOfCode = "func();".length;
804
- expect(flatToCollapsed(map, endOfCode)).toBe("```ts\nfunc();".length);
810
expect(flatToMarkdown(map, endOfCode)).toBe("```ts\nfunc();".length);
806
- expect(collapsedToFlat(map, flatToCollapsed(map, endOfCode))).toBe(endOfCode);
811
+ expect(markdownToFlat(map, flatToMarkdown(map, endOfCode))).toBe(endOfCode);
812
});
813
814
it("keeps the caret inside an empty fence", () => {
815
const value = "before\n```\n```";
816
const map = roundTrip(value);
817
const inside = "before\n".length;
813
- expect(flatToCollapsed(map, inside)).toBe("before\n```".length);
814
- expect(collapsedToFlat(map, flatToCollapsed(map, inside))).toBe(inside);
818
+ expect(flatToMarkdown(map, inside)).toBe("before\n```".length);
819
+ expect(markdownToFlat(map, flatToMarkdown(map, inside))).toBe(inside);
820
});
821
822
it("still places the end of an inline mark after its markers", () => {
@@ -823,12 +828,12 @@ describe("composer rich text document model", () => {
828
const value = "```ts\nab\n```";
829
const map = roundTrip(value);
830
expect(map.value).toBe(value);
826
- for (let collapsed = 0; collapsed <= "```ts\n".length; collapsed += 1) {
827
- expect(collapsedToFlat(map, collapsed)).toBe(0);
831
+ for (let markdown = 0; markdown <= "```ts\n".length; markdown += 1) {
832
+ expect(markdownToFlat(map, markdown)).toBe(0);
833
}
829
- expect(collapsedToFlat(map, "```ts\na".length)).toBe(1);
830
- for (let collapsed = "```ts\nab".length; collapsed <= value.length; collapsed += 1) {
831
- expect(collapsedToFlat(map, collapsed)).toBe(2);
834
+ expect(markdownToFlat(map, "```ts\na".length)).toBe(1);
835
+ for (let markdown = "```ts\nab".length; markdown <= value.length; markdown += 1) {
836
+ expect(markdownToFlat(map, markdown)).toBe(2);
837
}
838
});
839
@@ -910,19 +915,18 @@ describe("composer rich text document model", () => {
915
expect(roundTrip("```\ncode").value).toBe("```\ncode");
916
});
917
913
- it("counts a chip's source in a fence as one cursor position, as the draft store does", () => {
914
- const value = "```\nsee @b.md now\n```\nafter";
915
- const map = roundTrip(value);
918
+ it("keeps a chip's source in a fence as literal text", () => {
919
+ const value = "```\nsee @b.md and $babysit now\n```\nafter";
920
+ const known = () => ({ label: "Babysit", description: null });
921
+ const doc = ProseMirrorNode.fromJSON(schema, buildDocJson(value, known));
922
+ const map = serializeEditorDoc(doc);
923
expect(map.value).toBe(value);
924
+ expect(map.runs.filter((run) => run.kind === "token")).toEqual([]);
925
for (let flat = 0; flat <= map.docLength; flat += 1) {
918
- expect(flatToCollapsed(map, flat)).toBe(
919
- collapseExpandedComposerCursor(value, flatToMarkdown(map, flat)),
920
- );
926
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
927
}
922
- const afterChip = "see @b.md".length;
923
- expect(collapsedToFlat(map, flatToCollapsed(map, afterChip))).toBe(afterChip);
924
- const end = map.docLength;
925
- expect(collapsedToFlat(map, flatToCollapsed(map, end))).toBe(end);
928
+ // Reconciling against the provider's skills leaves the code alone too.
929
+ expect(skillChipReplacements(doc, known)).toEqual([]);
930
});
931
932
it("keeps fences literal in plain mode", () => {
@@ -930,12 +934,12 @@ describe("composer rich text document model", () => {
934
expect(roundTripPlain(value).value).toBe(value);
935
});
936
933
- it("maps every document offset through collapsed coordinates and back", () => {
937
+ it("maps every document offset through markdown coordinates and back", () => {
938
const value = "hi **bold** @README.md bye";
939
const map = roundTrip(value);
940
expect(map.value).toBe(value);
941
for (let flat = 0; flat <= map.docLength; flat += 1) {
938
- expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
942
+ expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
943
}
944
});
945
@@ -950,8 +954,9 @@ describe("composer rich text document model", () => {
954
expect(rich.value).toBe(value);
955
expect(plain.value).toBe(value);
956
for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {
953
- expect(flatToMarkdown(rich, collapsedToFlat(rich, collapsed))).toBe(
954
- flatToMarkdown(plain, collapsedToFlat(plain, collapsed)),
957
+ const markdown = expandCollapsedComposerCursor(value, collapsed);
958
+ expect(flatToMarkdown(rich, markdownToFlat(rich, markdown))).toBe(
959
+ flatToMarkdown(plain, markdownToFlat(plain, markdown)),
960
);
961
}
962
});
@@ -960,8 +965,8 @@ describe("composer rich text document model", () => {
965
const value = "a **bold** c";
966
const plain = roundTripPlain(value);
967
const rich = roundTrip(value);
963
- expect(flatToMarkdown(plain, collapsedToFlat(plain, 3))).toBe(3);
964
- expect(flatToMarkdown(rich, collapsedToFlat(rich, 3))).toBe(4);
968
+ expect(flatToMarkdown(plain, markdownToFlat(plain, 3))).toBe(3);
969
+ expect(flatToMarkdown(rich, markdownToFlat(rich, 3))).toBe(4);
970
});
971
972
it("maps markdown offsets at styled edges onto document text", () => {
@@ -970,8 +975,8 @@ describe("composer rich text document model", () => {
975
expect(map.value).toBe(value);
976
expect(flatToMarkdown(map, 2)).toBe(4);
977
expect(flatToMarkdown(map, 6)).toBe(10);
973
- expect(collapsedToFlat(map, 3)).toBe(2);
974
- expect(collapsedToFlat(map, 9)).toBe(6);
978
+ expect(markdownToFlat(map, 3)).toBe(2);
979
+ expect(markdownToFlat(map, 9)).toBe(6);
980
});
981
});
982
apps/web/src/composer-rich-text-doc.ts
+91
-100
@@ -432,10 +432,11 @@ interface DocLine {
432
inline: InlineJson[];
433
}
434
435
+/** Null for a `$name` that is not one of the provider's skills: it stays editable text. */
436
function atomJsonForSegment(
437
segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
437
- skillLabelFor: (name: string) => SkillMeta,
438
-): InlineJson {
438
+ skillLabelFor: (name: string) => SkillMeta | null,
439
+): InlineJson | null {
440
if (segment.type === "mention") {
441
return {
442
type: "composer-mention",
@@ -444,6 +445,7 @@ function atomJsonForSegment(
445
}
446
if (segment.type === "skill") {
447
const meta = skillLabelFor(segment.name);
448
+ if (!meta) return null;
449
return {
450
type: "composer-skill",
451
attrs: {
@@ -534,7 +536,7 @@ function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, un
536
*/
537
export function buildTiptapContent(
538
value: string,
537
- skillLabelFor: (name: string) => SkillMeta,
539
+ skillLabelFor: (name: string) => SkillMeta | null,
540
options?: { styling?: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number },
541
): Record<string, unknown>[] {
542
if (options?.literalText) {
@@ -573,7 +575,9 @@ export function buildTiptapContent(
575
return splitPromptIntoComposerSegments(chunk.text)
576
.map((segment) => {
577
if (segment.type === "text") return segment.text;
576
- atoms.push(atomJsonForSegment(segment, skillLabelFor));
578
+ const atom = atomJsonForSegment(segment, skillLabelFor);
579
+ if (!atom) return segment.source;
580
+ atoms.push(atom);
581
atomSources.push(segment.source);
582
return sentinel;
583
})
@@ -770,7 +774,7 @@ export function buildTiptapContent(
774
775
export function buildDocJson(
776
value: string,
773
- skillLabelFor: (name: string) => SkillMeta,
777
+ skillLabelFor: (name: string) => SkillMeta | null,
778
options?: { styling?: boolean; literalText?: boolean },
779
) {
780
const content = buildTiptapContent(value, skillLabelFor, options);
@@ -783,15 +787,12 @@ export interface RichRun {
787
/** Flat document offset (atoms count 1, markers excluded). */
788
flatStart: number;
789
docLen: number;
786
- /** Collapsed cursor length (markers literal, tokens count 1). */
787
- collapsedLen: number;
790
/** Markdown length (tokens expand to their source). */
791
mdLen: number;
792
openLen: number;
793
closeLen: number;
794
pmPos: number;
795
mdStart: number;
794
- collapsedStart: number;
796
nodeName?: string;
797
}
798
@@ -822,7 +823,6 @@ interface RichAccumulator {
823
runs: RichRun[];
824
value: string;
825
flat: number;
825
- collapsed: number;
826
md: number;
827
}
828
@@ -833,17 +833,14 @@ function pushBreakRun(acc: RichAccumulator, position?: number): void {
833
kind: "break",
834
flatStart: acc.flat,
835
docLen: 1,
836
- collapsedLen: 1,
836
mdLen: 1,
837
openLen: 0,
838
closeLen: 0,
839
pmPos,
840
mdStart: acc.md,
842
- collapsedStart: acc.collapsed,
841
});
842
acc.value += "\n";
843
acc.flat += 1;
846
- acc.collapsed += 1;
844
acc.md += 1;
845
}
846
@@ -867,16 +864,13 @@ function pushBlankLineRun(acc: RichAccumulator, pmPos: number): void {
864
kind: "prefix",
865
flatStart: acc.flat,
866
docLen: 0,
870
- collapsedLen: 1,
867
mdLen: 1,
868
openLen: 0,
869
closeLen: 0,
870
pmPos,
871
mdStart: acc.md,
876
- collapsedStart: acc.collapsed,
872
});
873
acc.value += "\n";
879
- acc.collapsed += 1;
874
acc.md += 1;
875
}
876
@@ -983,23 +977,19 @@ function appendInlineRuns(
977
const source = child.isText ? child.text! : readAtomSource(child);
978
const docLen = child.isText ? source.length : 1;
979
const mdText = open + source + close;
986
- const collapsedLen = open.length + docLen + close.length;
980
acc.runs.push({
981
kind: child.isText ? "text" : "token",
982
flatStart: acc.flat,
983
docLen,
991
- collapsedLen,
984
mdLen: mdText.length,
985
openLen: open.length,
986
closeLen: close.length,
987
pmPos,
988
mdStart: acc.md,
997
- collapsedStart: acc.collapsed,
989
...(child.isText ? {} : { nodeName: child.type.name }),
990
});
991
acc.value += mdText;
992
acc.flat += docLen;
1002
- acc.collapsed += collapsedLen;
993
acc.md += mdText.length;
994
});
995
if (children.length === 0) {
@@ -1007,13 +997,11 @@ function appendInlineRuns(
997
kind: "text",
998
flatStart: acc.flat,
999
docLen: 0,
1010
- collapsedLen: 0,
1000
mdLen: 0,
1001
openLen: 0,
1002
closeLen: 0,
1003
pmPos: contentStart,
1004
mdStart: acc.md,
1016
- collapsedStart: acc.collapsed,
1005
});
1006
}
1007
}
@@ -1202,16 +1190,13 @@ function walkList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator
1190
kind: "prefix",
1191
flatStart: acc.flat,
1192
docLen: 0,
1205
- collapsedLen: prefix.length,
1193
mdLen: prefix.length,
1194
openLen: 0,
1195
closeLen: 0,
1196
pmPos: itemContentStart + 1,
1197
mdStart: acc.md,
1211
- collapsedStart: acc.collapsed,
1198
});
1199
acc.value += prefix;
1214
- acc.collapsed += prefix.length;
1200
acc.md += prefix.length;
1201
let childPos = itemContentStart;
1202
let firstBlock = true;
@@ -1229,12 +1214,6 @@ function walkList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator
1214
});
1215
}
1216
1232
-/**
1233
- * The code is literal text in the editor, but the draft store still counts a
1234
- * chip's source in it as one cursor position, as it does everywhere. So the
1235
- * run splits at each chip source, which spans its characters in the document
1236
- * and one position in the collapsed space.
1237
- */
1217
function appendCodeBlockRun(
1218
block: ProseMirrorNode,
1219
pmPos: number,
@@ -1242,37 +1221,20 @@ function appendCodeBlockRun(
1221
acc: RichAccumulator,
1222
): void {
1223
const { open, content, close } = codeBlockSource(block, followed);
1245
- const pieces = content
1246
- ? splitPromptIntoComposerSegments(content).map((segment) =>
1247
- segment.type === "text"
1248
- ? { length: segment.text.length, collapsedLen: segment.text.length }
1249
- : { length: segment.source.length, collapsedLen: 1 },
1250
- )
1251
- : [{ length: 0, collapsedLen: 0 }];
1252
- let offset = 0;
1253
- pieces.forEach((piece, index) => {
1254
- const openLen = index === 0 ? open.length : 0;
1255
- const closeLen = index === pieces.length - 1 ? close.length : 0;
1256
- const collapsedLen = openLen + piece.collapsedLen + closeLen;
1257
- const mdLen = openLen + piece.length + closeLen;
1258
- acc.runs.push({
1259
- kind: "text",
1260
- flatStart: acc.flat,
1261
- docLen: piece.length,
1262
- collapsedLen,
1263
- mdLen,
1264
- openLen,
1265
- closeLen,
1266
- pmPos: pmPos + offset,
1267
- mdStart: acc.md,
1268
- collapsedStart: acc.collapsed,
1269
- nodeName: "codeBlock",
1270
- });
1271
- offset += piece.length;
1272
- acc.flat += piece.length;
1273
- acc.collapsed += collapsedLen;
1274
- acc.md += mdLen;
1224
+ const mdLen = open.length + content.length + close.length;
1225
+ acc.runs.push({
1226
+ kind: "text",
1227
+ flatStart: acc.flat,
1228
+ docLen: content.length,
1229
+ mdLen,
1230
+ openLen: open.length,
1231
+ closeLen: close.length,
1232
+ pmPos,
1233
+ mdStart: acc.md,
1234
+ nodeName: "codeBlock",
1235
});
1236
+ acc.flat += content.length;
1237
+ acc.md += mdLen;
1238
acc.value += open + content + close;
1239
}
1240
@@ -1288,16 +1250,13 @@ function walkBlockquote(quote: ProseMirrorNode, quoteStart: number, acc: RichAcc
1250
kind: "prefix",
1251
flatStart: acc.flat,
1252
docLen: 0,
1291
- collapsedLen: prefix.length,
1253
mdLen: prefix.length,
1254
openLen: 0,
1255
closeLen: 0,
1256
pmPos: childPos + 1,
1257
mdStart: acc.md,
1297
- collapsedStart: acc.collapsed,
1258
});
1259
acc.value += prefix;
1300
- acc.collapsed += prefix.length;
1260
acc.md += prefix.length;
1261
if (child.type.name === "paragraph") appendInlineRuns(child, childPos + 1, acc);
1262
childPos += child.nodeSize;
@@ -1327,7 +1286,7 @@ export function serializeSelection(doc: ProseMirrorNode, from: number, to: numbe
1286
}
1287
1288
export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
1330
- const acc: RichAccumulator = { runs: [], value: "", flat: 0, collapsed: 0, md: 0 };
1289
+ const acc: RichAccumulator = { runs: [], value: "", flat: 0, md: 0 };
1290
const blocks: ProseMirrorNode[] = [];
1291
doc.content.forEach((node) => {
1292
blocks.push(node);
@@ -1354,16 +1313,13 @@ export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
1313
kind: "prefix",
1314
flatStart: acc.flat,
1315
docLen: 0,
1357
- collapsedLen: prefix.length,
1316
mdLen: prefix.length,
1317
openLen: 0,
1318
closeLen: 0,
1319
pmPos: pmBlockStart + 1,
1320
mdStart: acc.md,
1363
- collapsedStart: acc.collapsed,
1321
});
1322
acc.value += prefix;
1366
- acc.collapsed += prefix.length;
1323
acc.md += prefix.length;
1324
appendInlineRuns(block, pmBlockStart + 1, acc);
1325
} else if (block.type.name === "horizontalRule") {
@@ -1373,16 +1329,13 @@ export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
1329
kind: "prefix",
1330
flatStart: acc.flat,
1331
docLen: 0,
1376
- collapsedLen: source.length,
1332
mdLen: source.length,
1333
openLen: 0,
1334
closeLen: 0,
1335
pmPos: pmBlockStart + block.nodeSize,
1336
mdStart: acc.md,
1382
- collapsedStart: acc.collapsed,
1337
});
1338
acc.value += source;
1385
- acc.collapsed += source.length;
1339
acc.md += source.length;
1340
} else if (block.type.name === "paragraph") {
1341
appendInlineRuns(block, pmBlockStart + 1, acc);
@@ -1398,12 +1351,64 @@ export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
1351
};
1352
}
1353
1401
-function lastRunEnd(map: RichDocMap, space: "collapsed" | "md"): number {
1402
- const last = map.runs[map.runs.length - 1];
1403
- if (!last) return 0;
1404
- return space === "collapsed"
1405
- ? last.collapsedStart + last.collapsedLen
1406
- : last.mdStart + last.mdLen;
1354
+export interface SkillChipReplacement {
1355
+ from: number;
1356
+ to: number;
1357
+ node: ProseMirrorNode;
1358
+}
1359
+
1360
+/**
1361
+ * Use the same Markdown token boundaries as draft restoration. Apply edits
1362
+ * last-first so positions stay valid and unrelated citation nodes keep their keys.
1363
+ */
1364
+export function skillChipReplacements(
1365
+ doc: ProseMirrorNode,
1366
+ skillLabelFor: (name: string) => SkillMeta | null,
1367
+): SkillChipReplacement[] {
1368
+ const schema = doc.type.schema;
1369
+ const skillType = schema.nodes["composer-skill"];
1370
+ if (!skillType) return [];
1371
+ const replacements: SkillChipReplacement[] = [];
1372
+ doc.descendants((node, pos) => {
1373
+ if (node.type !== skillType) return;
1374
+ const name = typeof node.attrs.skillName === "string" ? node.attrs.skillName : "";
1375
+ if (name && !skillLabelFor(name)) {
1376
+ replacements.push({
1377
+ from: pos,
1378
+ to: pos + node.nodeSize,
1379
+ node: schema.text(readAtomSource(node), node.marks),
1380
+ });
1381
+ }
1382
+ });
1383
+ const map = serializeEditorDoc(doc);
1384
+ let end = 0;
1385
+ for (const segment of splitPromptIntoComposerSegments(map.value)) {
1386
+ const start = end;
1387
+ end += segment.type === "text" ? segment.text.length : segment.source.length;
1388
+ if (segment.type !== "skill") continue;
1389
+ const meta = skillLabelFor(segment.name);
1390
+ if (!meta) continue;
1391
+ // Only text needs converting; an existing chip is a token run.
1392
+ const run = map.runs.find(
1393
+ (candidate) =>
1394
+ candidate.kind === "text" &&
1395
+ candidate.nodeName !== "codeBlock" &&
1396
+ start >= candidate.mdStart + candidate.openLen &&
1397
+ end <= candidate.mdStart + candidate.openLen + candidate.docLen,
1398
+ );
1399
+ if (!run) continue;
1400
+ const from = run.pmPos + (start - run.mdStart - run.openLen);
1401
+ replacements.push({
1402
+ from,
1403
+ to: from + segment.source.length,
1404
+ node: skillType.create(
1405
+ { skillName: segment.name, skillLabel: meta.label, skillDescription: meta.description },
1406
+ null,
1407
+ doc.nodeAt(from)?.marks,
1408
+ ),
1409
+ });
1410
+ }
1411
+ return replacements.sort((left, right) => right.from - left.from);
1412
}
1413
1414
/**
@@ -1417,23 +1422,6 @@ function runOwnsOffset(run: RichRun, flatOffset: number): boolean {
1422
return flatOffset < end || (flatOffset === end && run.nodeName === "codeBlock");
1423
}
1424
1420
-export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {
1421
- const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1422
- for (const run of map.runs) {
1423
- if (runOwnsOffset(run, bounded)) {
1424
- if (run.kind === "text" || run.kind === "token") {
1425
- const within = Math.min(
1426
- bounded - run.flatStart,
1427
- run.collapsedLen - run.openLen - run.closeLen,
1428
- );
1429
- return run.collapsedStart + run.openLen + within;
1430
- }
1431
- return run.collapsedStart + (bounded - run.flatStart);
1432
- }
1433
- }
1434
- return lastRunEnd(map, "collapsed");
1435
-}
1436
-
1425
export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
1426
const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1427
for (const run of map.runs) {
@@ -1444,21 +1432,24 @@ export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
1432
return run.mdStart + (bounded - run.flatStart);
1433
}
1434
}
1447
- return lastRunEnd(map, "md");
1435
+ const last = map.runs[map.runs.length - 1];
1436
+ return last ? last.mdStart + last.mdLen : 0;
1437
}
1438
1450
-export function collapsedToFlat(map: RichDocMap, collapsedOffset: number): number {
1439
+export function markdownToFlat(map: RichDocMap, markdownOffset: number): number {
1440
for (const run of map.runs) {
1452
- if (collapsedOffset < run.collapsedStart + run.collapsedLen) {
1441
+ if (markdownOffset < run.mdStart + run.mdLen) {
1442
if (run.kind === "prefix") return run.flatStart;
1443
if (run.kind === "text" || run.kind === "token") {
1455
- const within = collapsedOffset - run.collapsedStart;
1456
- const contentLen = run.collapsedLen - run.openLen - run.closeLen;
1444
+ const within = markdownOffset - run.mdStart;
1445
if (within <= run.openLen) return run.flatStart;
1458
- if (within >= run.openLen + contentLen) return run.flatStart + run.docLen;
1446
+ // A chip is one document position however long its source is.
1447
+ if (run.kind === "token" || within >= run.openLen + run.docLen) {
1448
+ return run.flatStart + run.docLen;
1449
+ }
1450
return run.flatStart + (within - run.openLen);
1451
}
1461
- return run.flatStart + (collapsedOffset - run.collapsedStart);
1452
+ return run.flatStart + (markdownOffset - run.mdStart);
1453
}
1454
}
1455
return map.docLength;