Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): Pi skill 胶囊与其它 harness 展示对齐 (#2847)

Dashc5e6658e80e6
diff --git a/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx b/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx
index 27bfc3699b..969737a56a 100644
--- a/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx
@@ -64,6 +64,23 @@ describe('SentInlineAtomBody', () => {
expect(document.querySelector('[tabindex]')).toBeNull();
});
+ it('does not turn unconfirmed /skill: prose into a /unknown chip', () => {
+ render(<SentInlineAtomBody content="/skill:unknown is prose" />);
+ expect(screen.getByText(/\/skill:unknown is prose/)).toBeTruthy();
+ expect(screen.queryByText('/unknown')).toBeNull();
+ });
+
+ it('still projects a confirmed /skill:git range to /git', () => {
+ render(
+ <SentInlineAtomBody
+ content="/skill:git follow-up"
+ slashCommandRanges={[{ start: 0, end: 10 }]}
+ />,
+ );
+ expect(screen.getByText('/git')).toBeTruthy();
+ expect(screen.queryByText('/skill:git')).toBeNull();
+ });
+
it('leaves the pending queue single-line truncation contract to the row container', () => {
const bodyStart = pendingQueueSource.indexOf('<SentInlineAtomBody');
const bodyEnd = pendingQueueSource.indexOf('/>', bodyStart);
diff --git a/apps/desktop/src/renderer/__tests__/slashCommandDecoration.test.ts b/apps/desktop/src/renderer/__tests__/slashCommandDecoration.test.ts
index 9fff89dda3..c8686c34a4 100644
--- a/apps/desktop/src/renderer/__tests__/slashCommandDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/slashCommandDecoration.test.ts
@@ -103,4 +103,34 @@ describe('SlashCommandDecoration', () => {
expect(state.doc.firstChild?.firstChild?.isText).toBe(true);
expect(decorationRanges(plugin, state)).toEqual([{ from: 1, to: 7 }]);
});
+
+ it('matches Pi runtime aliases and hides the skill: prefix', () => {
+ const commands = [{
+ kind: 'agent-skill' as const,
+ name: 'git',
+ description: 'git skill',
+ source: 'skill' as const,
+ runtimeCommandName: 'skill:git',
+ }];
+ const source = doc(p(txt('/skill:git follow /git')));
+
+ expect(findSlashCommandMatches(source, commands)).toMatchObject([
+ { from: 1, to: 11, command: { name: 'git' } },
+ { from: 19, to: 23, command: { name: 'git' } },
+ ]);
+
+ const plugin = createSlashCommandPlugin();
+ let state = EditorState.create({
+ schema,
+ doc: source,
+ plugins: [plugin],
+ });
+ state = state.apply(state.tr.setMeta('slashCommandDecoration', commands));
+
+ expect(decorationRanges(plugin, state)).toEqual([
+ { from: 1, to: 11 },
+ { from: 2, to: 8 },
+ { from: 19, to: 23 },
+ ]);
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts b/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
index 70c5a11fa6..82b951a5b0 100644
--- a/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/slashPaletteEmptyResultGuard.test.ts
@@ -23,4 +23,13 @@ describe('slash palette empty-result keyboard guard', () => {
selectionBlock.indexOf('if (\n atOpen'),
);
});
+
+ it('inserts the human command name so Pi runtime aliases stay off the display layer', () => {
+ const insertBlock = chatInputSource.slice(
+ chatInputSource.indexOf('const insertSlashCommand = useCallback'),
+ chatInputSource.indexOf('const resolveEffectiveAtRange'),
+ );
+ expect(insertBlock).toContain('cmd.name');
+ expect(insertBlock).not.toContain('slashCommandInvocationName');
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
index 8e6554d201..65b2eb077d 100644
--- a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
+++ b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
@@ -181,6 +181,67 @@ describe('UserMessageEditBox — idle 发送', () => {
expect(commitMock.mock.calls[0][0].slashCommandRanges).toBeUndefined();
});
+ it('未确认的 /skill: 散文被用户删掉前缀后不再静默改回 runtime 名', async () => {
+ const box = renderBox({
+ initialText: '/skill:unknown is prose',
+ slashCommandRanges: [],
+ });
+ fireEvent.change(box.textarea, { target: { value: '/unknown is prose' } });
+ fireEvent.click(box.sendBtn);
+ await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
+ expect(commitMock.mock.calls[0][0].text).toBe('/unknown is prose');
+ expect(commitMock.mock.calls[0][0].slashCommandRanges).toBeUndefined();
+ });
+
+ it('后文已确认的命令 range 不会让首行未确认的 /skill: 散文被改回', async () => {
+ const original = '/skill:unknown\n/help later';
+ const helpStart = original.indexOf('/help');
+ const box = renderBox({
+ initialText: original,
+ initialSubmitText: original,
+ slashCommandRanges: [{ start: helpStart, end: helpStart + 5 }],
+ });
+ fireEvent.change(box.textarea, { target: { value: '/unknown\n/help later' } });
+ fireEvent.click(box.sendBtn);
+ await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
+ expect(commitMock.mock.calls[0][0].text).toBe('/unknown\n/help later');
+ expect(commitMock.mock.calls[0][0].slashCommandRanges).toBeUndefined();
+ });
+
+ it('已确认 range 覆盖的 Pi skill 编辑后仍恢复 runtime 名', async () => {
+ const box = renderBox({
+ initialText: '/git please',
+ initialSubmitText: '/skill:git please',
+ slashCommandRanges: [{ start: 0, end: 10 }],
+ });
+ fireEvent.change(box.textarea, { target: { value: '/git review' } });
+ fireEvent.click(box.sendBtn);
+ await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
+ expect(commitMock.mock.calls[0][0].text).toBe('/skill:git review');
+ expect(commitMock.mock.calls[0][0].slashCommandRanges).toEqual([{ start: 0, end: 10 }]);
+ });
+
+ it('引用 marker 落库坐标仍能恢复可见 /git',
+ async () => {
+ const wire = [
+ '> <!-- cindy-composer-quote -->',
+ '> quoted',
+ '',
+ '/skill:git follow-up',
+ ].join('\n');
+ const skillStart = wire.indexOf('/skill:git');
+ const box = renderBox({
+ initialText: 'quoted\n\n/git follow-up',
+ initialSubmitText: wire,
+ quotesEncoded: true,
+ slashCommandRanges: [{ start: skillStart, end: skillStart + 10 }],
+ });
+ fireEvent.change(box.textarea, { target: { value: 'quoted\n\n/git please' } });
+ fireEvent.click(box.sendBtn);
+ await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
+ expect(commitMock.mock.calls[0][0].text).toBe('quoted\n\n/skill:git please');
+ });
+
it('被拦消息覆盖重发在文本未修改时透传语义引用与 chip ranges', async () => {
const override = vi.fn(async () => {});
const agentReferences = [{
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index ba6690b892..b46ba481b0 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -26,6 +26,10 @@ import {
Target,
} from 'lucide-react';
import { readAgentInputReferences } from '@cindy/maker-shared/agent-input-projection';
+import {
+ projectSlashCommandsInText,
+ slashCommandDisplayLabel,
+} from '@cindy/maker-shared/composer-palette';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { cn } from '@/lib/utils';
@@ -526,11 +530,12 @@ function renderContentWithoutPastedText(
// Check for /command at line start — only if it looks like a real command
const slashMatch = line.match(/^\/(\S+)/);
if (renderLegacySlashCommands && slashMatch && looksLikeCommand(slashMatch[1])) {
+ const slashLabel = `/${slashMatch[1]}`;
nodes.push(
<InlineReferenceChip
key={`s-${li}`}
- label={`/${slashMatch[1]}`}
- tooltip={`/${slashMatch[1]}`}
+ label={slashLabel}
+ tooltip={slashLabel}
className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle text-[var(--msg-user-text)]"
/>,
);
@@ -857,11 +862,12 @@ export function renderContent(
const useLegacySlashHeuristic = slashCommandRanges === undefined;
return tokens.map((token, index) => {
if (token.kind === 'slash') {
+ const slashLabel = slashCommandDisplayLabel(token.text);
return (
<InlineReferenceChip
key={`slash-chip-${index}`}
- label={token.text}
- tooltip={token.text}
+ label={slashLabel}
+ tooltip={slashLabel}
className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle text-[var(--msg-user-text)]"
/>
);
@@ -1139,7 +1145,16 @@ export function UserMessage({
// copy text per V1.2: original text + (if files) "\n\n附件:a.md, b.md"
// ghost-summon-card:copy 给用户的是"他自己的话"(剥离机器追加段);
// 追加段原文在卡片展开区可查可选中。
- const copyBody = quotesEncoded ? stripChatQuoteMarkerLines(ghostBody) : ghostBody;
+ // Project on the persisted wire text first so slashCommandRanges stay valid,
+ // then strip private quote markers for copy / edit display.
+ const projectedSource = projectSlashCommandsInText(ghostBody, slashCommandRanges);
+ const copyBody = quotesEncoded ? stripChatQuoteMarkerLines(projectedSource) : projectedSource;
+ const visibleSource = quotesEncoded ? stripChatQuoteMarkerLines(ghostBody) : ghostBody;
+ const editSubmitText = quotesEncoded
+ ? ghostBody
+ : copyBody !== visibleSource
+ ? visibleSource
+ : undefined;
const copyText = hasFiles
? `${copyBody}\n\n${t('chat.userMessage.attachmentPrefix')}${files!.map((f) => f.name).join(', ')}`
: copyBody;
@@ -1467,7 +1482,7 @@ export function UserMessage({
sessionId={sessionId}
messageClientId={messageClientId}
initialText={copyBody}
- initialSubmitText={quotesEncoded ? ghostBody : undefined}
+ initialSubmitText={editSubmitText}
images={images}
files={files}
workingDir={workingDir}
diff --git a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
index 4c8147209f..a7c1631cc3 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
@@ -30,6 +30,12 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import {
+ findSlashCommandToken,
+ leadingSlashCommandRange,
+ restoreSlashCommandRuntimeAlias,
+ slashCommandRangeCoversToken,
+} from '@cindy/maker-shared/composer-palette';
import { cn } from '@/lib/utils';
import { Spinner } from '@/components/ui/spinner';
import { ListComposerTextarea } from '@/components/new-chat/ListComposerTextarea';
@@ -172,7 +178,14 @@ export function UserMessageEditBox({
const doCommit = useCallback(async () => {
try {
const visibleTextUnchanged = text === initialText;
- const submitText = visibleTextUnchanged ? (initialSubmitText ?? text) : text;
+ const originalWireText = initialSubmitText ?? initialText;
+ const originalHadConfirmedRange = slashCommandRangeCoversToken(
+ slashCommandRanges,
+ findSlashCommandToken(originalWireText),
+ );
+ const submitText = visibleTextUnchanged
+ ? originalWireText
+ : restoreSlashCommandRuntimeAlias(originalWireText, text, slashCommandRanges);
const preserveQuoteMetadata = quotesEncoded && visibleTextUnchanged;
const preservedAgentReferences =
visibleTextUnchanged && agentReferences && agentReferences.length > 0
@@ -182,9 +195,14 @@ export function UserMessageEditBox({
visibleTextUnchanged && pastedTextRanges && pastedTextRanges.length > 0
? [...pastedTextRanges]
: undefined;
- const preservedSlashCommandRanges =
- visibleTextUnchanged && slashCommandRanges !== undefined
- ? [...slashCommandRanges]
+ const rebuiltSlashRange = leadingSlashCommandRange(submitText);
+ const submitTokenIsRuntimeAlias = rebuiltSlashRange
+ ? submitText.slice(rebuiltSlashRange.start, rebuiltSlashRange.end).toLowerCase().startsWith('/skill:')
+ : false;
+ const preservedSlashCommandRanges = visibleTextUnchanged && slashCommandRanges !== undefined
+ ? [...slashCommandRanges]
+ : submitTokenIsRuntimeAlias && originalHadConfirmedRange && rebuiltSlashRange
+ ? [rebuiltSlashRange]
: undefined;
if (onCommitOverride) {
// 被拦消息:普通重发(不 rewind)。失败抛错落入下方 catch 保留编辑态。
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 62205800c2..8a578d04f7 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -231,7 +231,6 @@ import {
loadAllCommands,
nextAvailableSlashCommandIndex,
PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
- slashCommandInvocationName,
type SlashCommandRosterState,
type UnifiedCommand,
} from '@/lib/slashCommands';
@@ -4632,14 +4631,13 @@ export function ChatInput({
// 识别并追加机器指令,序列化零特判。
tr.replaceWith(from, runEnd, editor.schema.text(`$${cmd.name} `));
} else {
- // Slash 也保持纯文本;SlashCommandDecoration 只负责视觉确认,
- // Backspace / 光标移动因此与普通文字完全一致。
+ // 展示层写入人类名(`/git`);Pi 线路名(`/skill:git`)只在发送期改写。
replaceSlashCommandRunWithText(
tr,
editor.schema,
from,
runEnd,
- slashCommandInvocationName(cmd),
+ cmd.name,
);
}
return true;
diff --git a/apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts b/apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts
index 1c76736cfd..363f79750e 100644
--- a/apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts
@@ -14,12 +14,17 @@ import type { Node as PMNode, Schema } from '@tiptap/pm/model';
import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import { slashCommandRuntimePrefixLength } from '@cindy/maker-shared/composer-palette';
+
import type { UnifiedCommand } from '@/lib/slashCommands';
const PLUGIN_KEY = new PluginKey<SlashCommandPluginState>('slashCommandDecoration');
const META_KEY = 'slashCommandDecoration';
-export type SlashCommandRoster = ReadonlyArray<Pick<UnifiedCommand, 'name' | 'description'>>;
+export type SlashCommandRosterItem = Pick<UnifiedCommand, 'name' | 'description'> & {
+ runtimeCommandName?: string;
+};
+export type SlashCommandRoster = ReadonlyArray<SlashCommandRosterItem>;
interface SlashCommandPluginState {
commands: SlashCommandRoster;
@@ -29,7 +34,7 @@ interface SlashCommandPluginState {
export interface SlashCommandMatch {
from: number;
to: number;
- command: Pick<UnifiedCommand, 'name' | 'description'>;
+ command: SlashCommandRosterItem;
}
function previousInlineAllowsSlash(parent: PMNode, childIndex: number): boolean {
@@ -52,10 +57,13 @@ export function findSlashCommandMatches(
commands: SlashCommandRoster,
): SlashCommandMatch[] {
if (commands.length === 0) return [];
- const byName = new Map<string, Pick<UnifiedCommand, 'name' | 'description'>>();
+ const byName = new Map<string, SlashCommandRosterItem>();
for (const command of commands) {
const name = command.name.trim();
if (name) byName.set(name.toLowerCase(), command);
+ const runtime = command.runtimeCommandName?.trim();
+ // Palette shows `git`; Pi wire form is `skill:git`. Both must light the pill.
+ if (runtime) byName.set(runtime.toLowerCase(), command);
}
if (byName.size === 0) return [];
@@ -83,9 +91,7 @@ export function findSlashCommandMatches(
return matches;
}
-function slashPillAttrs(
- command: Pick<UnifiedCommand, 'name' | 'description'>,
-): Record<string, string> {
+function slashPillAttrs(command: SlashCommandRosterItem): Record<string, string> {
return {
class: 'slash-cmd-pill',
'data-slash-command': command.name,
@@ -96,10 +102,20 @@ function slashPillAttrs(
function buildDecorations(doc: PMNode, commands: SlashCommandRoster): DecorationSet {
const matches = findSlashCommandMatches(doc, commands);
if (matches.length === 0) return DecorationSet.empty;
- return DecorationSet.create(
- doc,
- matches.map((match) => Decoration.inline(match.from, match.to, slashPillAttrs(match.command))),
- );
+ const decorations: Decoration[] = [];
+ for (const match of matches) {
+ const token = doc.textBetween(match.from, match.to);
+ const prefixLength = slashCommandRuntimePrefixLength(token, match.command);
+ if (prefixLength > 0) {
+ decorations.push(
+ Decoration.inline(match.from + 1, match.from + 1 + prefixLength, {
+ class: 'slash-cmd-runtime-prefix',
+ }),
+ );
+ }
+ decorations.push(Decoration.inline(match.from, match.to, slashPillAttrs(match.command)));
+ }
+ return DecorationSet.create(doc, decorations);
}
/** Palette 选择后用普通文本替换 slash run,不创建 mentionChip atom。 */
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 6fdeea2bba..c60deaabb4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -144,6 +144,7 @@ import { useAnimatedNumber } from '@/hooks/useAnimatedNumber';
import {
loadAllCommands,
dispatchCommand,
+ leadingSlashInvocation,
PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
rebaseInlineRangesAfterSlashCommandRewrite,
reconcilePiRuntimeCommandForDispatch,
@@ -2498,9 +2499,13 @@ export function CCAgentSessionView({
},
): Promise<{ handled: boolean; accepted: boolean; message: string }> => {
const slashMatch = message.match(/^\/(\S+)(?:\s+(.*))?$/s);
- if (!slashMatch) return { handled: false, accepted: false, message };
- const cmdName = slashMatch[1].toLowerCase();
- const args = slashMatch[2] ?? '';
+ const agentKind = dbToMakerAgentKind(session?.agentKind);
+ const leading = !slashMatch && agentKind === 'pi'
+ ? leadingSlashInvocation(message)
+ : undefined;
+ if (!slashMatch && !leading) return { handled: false, accepted: false, message };
+ const cmdName = (slashMatch?.[1] ?? leading!.name).toLowerCase();
+ const args = slashMatch?.[2] ?? '';
const allowDesktopDispatch = options?.allowDesktopDispatch ?? true;
const workingDir = options?.workingDirOverride ?? session?.workingDir;
const cached = allCommandsRef.current;
@@ -2511,7 +2516,6 @@ export function CCAgentSessionView({
: cached.length > 0
? cached
: await getHelpCommandsSnapshot();
- const agentKind = dbToMakerAgentKind(session?.agentKind);
const reconcileParams = {
agentKind,
sessionId: session?.id,
@@ -2549,6 +2553,8 @@ export function CCAgentSessionView({
agentKind === 'pi' ? rewriteAgentSkillInvocationForDispatch(message, hit) : message,
};
}
+ // Desktop commands stay `^/` only. A whitespace-prefixed `/help` is not a dispatch.
+ if (!slashMatch) return { handled: false, accepted: false, message };
if (!allowDesktopDispatch) return { handled: false, accepted: false, message };
// Review is handed to Main immediately with this invocation's serialized
// attachments. It must not depend on this React view remaining mounted,
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 53835e89f5..1cae85f35d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -125,6 +125,10 @@ import { NewGoalDialog } from '@/components/new-chat/NewGoalDialog';
import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
import type { GoalLimitValues } from '@/components/new-chat/GoalAdvancedLimits';
import { makerChatStore } from '@/lib/makerChatStore';
+import {
+ rebaseInlineRangesAfterSlashCommandRewrite,
+ rewritePiSkillMessageForSend,
+} from '@/lib/slashCommands';
import { worktreeCreationStore } from '@/lib/worktreeCreationStore';
import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
import { crossAgentConvertService } from '@/lib/crossAgentConvertService';
@@ -3806,9 +3810,21 @@ export function NewMakerDraftRoute() {
}
}
+ const dispatchedMessage = await rewritePiSkillMessageForSend({
+ agentKind: persistedAgentKind === 'cc' ? 'claude-code' : persistedAgentKind,
+ message,
+ workingDir: newDir,
+ sessionId: newSession.id,
+ });
+ const rebaseRanges = <T extends { start: number; end: number }>(
+ ranges: readonly T[] | undefined,
+ ): T[] | undefined => {
+ if (!ranges) return undefined;
+ return rebaseInlineRangesAfterSlashCommandRewrite(ranges, message, dispatchedMessage);
+ };
const accepted = await makerChatStore.sendMessage(
newSession.id,
- message,
+ dispatchedMessage,
model,
effort,
permissionMode,
@@ -3818,13 +3834,13 @@ export function NewMakerDraftRoute() {
{
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
...(opts?.agentReferences?.length
- ? { agentReferences: opts.agentReferences }
+ ? { agentReferences: rebaseRanges(opts.agentReferences) }
: {}),
...(opts?.pastedTextRanges?.length
- ? { pastedTextRanges: opts.pastedTextRanges }
+ ? { pastedTextRanges: rebaseRanges(opts.pastedTextRanges) }
: {}),
...(opts?.slashCommandRanges !== undefined
- ? { slashCommandRanges: opts.slashCommandRanges }
+ ? { slashCommandRanges: rebaseRanges(opts.slashCommandRanges) }
: {}),
},
);
diff --git a/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts b/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts
index 6e783e4233..7658c72af4 100644
--- a/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/slashCommands.test.ts
@@ -12,6 +12,8 @@ import {
reconcilePiRuntimeCommandForDispatch,
reconcilePiRuntimeCommandForDispatchWithRetry,
rewriteAgentSkillInvocationForDispatch,
+ rewritePiSkillAliasFromCommand,
+ rewritePiSkillMessageForSend,
slashCommandInvocationName,
type UnifiedCommand,
} from '@/lib/slashCommands';
@@ -35,6 +37,13 @@ describe('rewriteAgentSkillInvocationForDispatch', () => {
expect(rewriteAgentSkillInvocationForDispatch('/demo keep spacing', loaded)).toBe(
'/skill:demo keep spacing',
);
+ expect(rewriteAgentSkillInvocationForDispatch(' \n/demo keep', loaded)).toBe(
+ ' \n/skill:demo keep',
+ );
+ expect(rewriteAgentSkillInvocationForDispatch('please /demo', loaded)).toBe('please /demo');
+ expect(rewriteAgentSkillInvocationForDispatch('> quoted\n\n/demo', loaded)).toBe(
+ '> quoted\n\n/demo',
+ );
});
it('rebases command and later inline metadata when the runtime alias grows', () => {
@@ -54,6 +63,18 @@ describe('rewriteAgentSkillInvocationForDispatch', () => {
{ start: 12, end: 17, kind: 'reference' },
{ start: 18, end: 24, kind: 'paste' },
]);
+
+ expect(rebaseInlineRangesAfterSlashCommandRewrite(
+ [
+ { start: 3, end: 8, kind: 'slash' },
+ { start: 9, end: 14, kind: 'reference' },
+ ],
+ ' \n/demo @task',
+ ' \n/skill:demo @task',
+ )).toEqual([
+ { start: 3, end: 14, kind: 'slash' },
+ { start: 15, end: 20, kind: 'reference' },
+ ]);
});
it('does not rewrite unavailable, mismatched, or non-skill commands', () => {
@@ -72,6 +93,26 @@ describe('rewriteAgentSkillInvocationForDispatch', () => {
})).toBe('/other');
expect(rewriteAgentSkillInvocationForDispatch('/demo', desktop)).toBe('/demo');
});
+
+ it('leaves non-Pi first messages untouched without loading a roster', async () => {
+ await expect(rewritePiSkillMessageForSend({
+ agentKind: 'codex',
+ message: '/git please',
+ })).resolves.toBe('/git please');
+ });
+
+ it('rewrites a discovered Pi project skill that already has a runtime alias', () => {
+ const discovered = skill({
+ name: 'git',
+ scope: 'repo',
+ runtimeStatus: 'discovered',
+ runtimeCommandName: 'skill:git',
+ });
+ expect(rewriteAgentSkillInvocationForDispatch('/git please', discovered)).toBe('/git please');
+ expect(rewritePiSkillAliasFromCommand('/git please', discovered)).toBe('/skill:git please');
+ expect(rewritePiSkillAliasFromCommand(' \n/git please', discovered)).toBe(' \n/skill:git please');
+ expect(rewritePiSkillAliasFromCommand('note /git', discovered)).toBe('note /git');
+ });
});
describe('filterSlashCommands', () => {
@@ -162,7 +203,7 @@ describe('Pi project skill availability', () => {
expect(isSlashCommandUnavailable(skill({ scope: 'repo' }))).toBe(false);
});
- it('keeps the palette label while invoking Pi skills by their runtime command name', () => {
+ it('keeps the palette / composer label while invoking Pi skills by their runtime command name', () => {
const loaded = skill({
name: 'demo',
scope: 'repo',
diff --git a/apps/desktop/src/renderer/lib/slashCommands.ts b/apps/desktop/src/renderer/lib/slashCommands.ts
index 4143afe532..15ff1bb12c 100644
--- a/apps/desktop/src/renderer/lib/slashCommands.ts
+++ b/apps/desktop/src/renderer/lib/slashCommands.ts
@@ -17,6 +17,9 @@
*/
import type { UnifiedCommand, AgentKind } from '@cindy/maker-core';
+import { leadingSlashInvocation } from '@cindy/maker-shared';
+
+export { leadingSlashInvocation };
import { createLogger } from '@/lib/logger';
@@ -44,8 +47,8 @@ export function slashCommandInvocationName(command: UnifiedCommand): string {
}
/**
- * Palette selection already inserts runtimeCommandName. Apply the same mapping
- * to a matching command that the user typed or pasted directly before send.
+ * Palette / composer keep the human name (`/git`). Rewrite only at dispatch so
+ * Pi receives the runtime alias (`/skill:git`) without leaking it into the UI.
*/
export function rewriteAgentSkillInvocationForDispatch(
message: string,
@@ -59,9 +62,43 @@ export function rewriteAgentSkillInvocationForDispatch(
) {
return message;
}
- const match = message.match(/^\/(\S+)([\s\S]*)$/);
- if (!match || match[1].toLowerCase() !== command.name.toLowerCase()) return message;
- return `/${command.runtimeCommandName}${match[2]}`;
+ const leading = leadingSlashInvocation(message);
+ if (!leading || leading.name.toLowerCase() !== command.name.toLowerCase()) return message;
+ return `${message.slice(0, leading.start)}/${command.runtimeCommandName}${message.slice(leading.end)}`;
+}
+
+/** Rewrite `/git` → `/skill:git` even when the skill is still `discovered`. */
+export function rewritePiSkillAliasFromCommand(
+ message: string,
+ command: UnifiedCommand | undefined,
+): string {
+ const leading = leadingSlashInvocation(message);
+ if (
+ !leading
+ || command?.kind !== 'agent-skill'
+ || !command.runtimeCommandName
+ || leading.name.toLowerCase() !== command.name.toLowerCase()
+ ) {
+ return rewriteAgentSkillInvocationForDispatch(message, command);
+ }
+ return `${message.slice(0, leading.start)}/${command.runtimeCommandName}${message.slice(leading.end)}`;
+}
+
+/** First-message / worktree send paths that skip SessionView dispatch. */
+export async function rewritePiSkillMessageForSend(params: {
+ agentKind: AgentKind;
+ message: string;
+ workingDir?: string | null;
+ sessionId?: string;
+}): Promise<string> {
+ if (params.agentKind !== 'pi') return params.message;
+ const leading = leadingSlashInvocation(params.message);
+ if (!leading) return params.message;
+ const commands = await loadAllCommands(params.agentKind, params.workingDir, {
+ ...(params.sessionId ? { sessionId: params.sessionId } : {}),
+ });
+ const hit = commands.find((command) => command.name.toLowerCase() === leading.name.toLowerCase());
+ return rewritePiSkillAliasFromCommand(params.message, hit);
}
/**
@@ -74,12 +111,13 @@ export function rebaseInlineRangesAfterSlashCommandRewrite<T extends { start: nu
rewrittenMessage: string,
): T[] {
if (originalMessage === rewrittenMessage) return [...ranges];
- const originalCommand = originalMessage.match(/^\/\S+/)?.[0];
- const rewrittenCommand = rewrittenMessage.match(/^\/\S+/)?.[0];
+ const originalCommand = leadingSlashInvocation(originalMessage);
+ const rewrittenCommand = leadingSlashInvocation(rewrittenMessage);
if (!originalCommand || !rewrittenCommand) return [...ranges];
- const boundary = originalCommand.length;
- const delta = rewrittenCommand.length - boundary;
+ const boundary = originalCommand.end;
+ const delta = (rewrittenCommand.end - rewrittenCommand.start)
+ - (originalCommand.end - originalCommand.start);
if (delta === 0) return [...ranges];
return ranges.map((range) => ({
...range,
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index f2508b0ae3..5b93af02e9 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -747,17 +747,43 @@ html:lang(ko) {
}
/* Slash 指令确认胶囊 — doc 里仍是普通 `/command` 文本。字号、字重和文字色
- 完全继承 composer 正文;仅用 surface/border/radius 表达“已命中命令”。 */
+ 完全继承 composer 正文;仅用 surface/border/radius 表达“已命中命令”。
+ inline-flex 让 padding 进布局,避免行首悬挂绘制溢出输入卡片。 */
.ProseMirror .slash-cmd-pill {
+ display: inline-flex;
+ align-items: center;
+ box-sizing: border-box;
background: var(--surface-chip);
border: 1px solid var(--border-default);
border-radius: 9999px;
padding: 2px 8px 3px;
+ margin-inline: 0 4px;
color: var(--chat-input-text);
font: inherit;
box-decoration-break: clone;
-webkit-box-decoration-break: clone;
}
+/* Pi 线路名 `/skill:git` 里的 `skill:` 只做识别:展示层与 CC/Codex 一样只留 `/git`。 */
+.ProseMirror .slash-cmd-runtime-prefix {
+ display: none;
+}
+/* 隐藏 runtime 前缀后 ProseMirror 会把胶囊切成相邻 span,接缝拼回一颗。 */
+.ProseMirror .slash-cmd-pill:has(+ .slash-cmd-pill),
+.ProseMirror .slash-cmd-pill:has(+ .slash-cmd-runtime-prefix) {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ border-right: 0;
+ margin-right: 0;
+ padding-right: 0;
+}
+.ProseMirror .slash-cmd-pill + .slash-cmd-pill,
+.ProseMirror .slash-cmd-runtime-prefix + .slash-cmd-pill {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ border-left: 0;
+ margin-left: 0;
+ padding-left: 0;
+}
/* 快速开始预填胶囊 — QuickStartPillMark。点击 New Maker 快速开始卡片后
预填文本以此 mark 包裹,渲染为与 ModelPromotionBadge 同色系的圆角
diff --git a/apps/mobile/src/__tests__/messageActions.test.ts b/apps/mobile/src/__tests__/messageActions.test.ts
index 7eb1b838d1..1ea0c6f84a 100644
--- a/apps/mobile/src/__tests__/messageActions.test.ts
+++ b/apps/mobile/src/__tests__/messageActions.test.ts
@@ -84,6 +84,29 @@ describe('messageActions', () => {
expect(mobileMessageShowsActionBar({ ...base, hasSystemCard: true, kind: 'user' })).toBe(false);
});
+ it('projects confirmed Pi runtime /skill: aliases when copying a user message', () => {
+ expect(buildMobileMessageCopyText(normalizedMessage({
+ body: '/skill:git follow-up review',
+ slashCommandRanges: [{ start: 0, end: 10 }],
+ }))).toBe('/git follow-up review');
+ expect(buildMobileMessageCopyText(normalizedMessage({
+ body: '/skill:git is just prose here',
+ }))).toBe('/skill:git is just prose here');
+ const quoted = [
+ '> <!-- cindy-composer-quote -->',
+ '> quoted',
+ '',
+ '/skill:git follow-up review',
+ ].join('\n');
+ expect(buildMobileMessageCopyText(normalizedMessage({
+ body: quoted,
+ quotesEncoded: true,
+ slashCommandRanges: [
+ { start: quoted.indexOf('/skill:git'), end: quoted.indexOf('/skill:git') + 10 },
+ ],
+ }))).toBe(['> quoted', '', '/git follow-up review'].join('\n'));
+ });
+
it('builds desktop-compatible copy text with attachment names', () => {
expect(buildMobileMessageCopyText(normalizedMessage({
body: 'Please inspect this.',
diff --git a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
index 12a4f7c61d..ecc7fb6bc0 100644
--- a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
+++ b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
@@ -88,4 +88,12 @@ describe('sent message atoms', () => {
[{ start, end: start + 'private payload'.length, display: 'Pasted text (1 line)' }],
))).toBe('before Pasted text (1 line) after');
});
+
+ it('projects Pi runtime /skill: chips to the human slash label', () => {
+ expect(sentInlineTokensDisplayText(buildSentInlineTokens(
+ '/skill:git follow-up',
+ [],
+ [{ start: 0, end: 10 }],
+ ))).toBe('/git follow-up');
+ });
});
diff --git a/apps/mobile/src/session/SentInlineAtomBody.tsx b/apps/mobile/src/session/SentInlineAtomBody.tsx
index 8926855544..1896788dbb 100644
--- a/apps/mobile/src/session/SentInlineAtomBody.tsx
+++ b/apps/mobile/src/session/SentInlineAtomBody.tsx
@@ -6,6 +6,7 @@ import {
type TextStyle,
type ViewStyle,
} from "react-native";
+import { slashCommandDisplayLabel } from "@cindy/maker-shared/composer-palette";
import { FileText } from "lucide-react-native";
import { Text } from "@/components/AppText";
import { InlineQuoteChip } from "@/session/InlineQuoteChip";
@@ -100,11 +101,12 @@ export function SentInlineAtomBody({
);
}
if (token.kind === "slash") {
+ const slashLabel = slashCommandDisplayLabel(token.text);
return (
<InlineReferenceChip
- accessibilityLabel={token.text}
+ accessibilityLabel={slashLabel}
key={`slash:${index}`}
- label={token.text}
+ label={slashLabel}
testID="message.slashCommandChip"
/>
);
diff --git a/apps/mobile/src/session/conversationShareProjection.ts b/apps/mobile/src/session/conversationShareProjection.ts
index 4dd3771cc9..165274f4fd 100644
--- a/apps/mobile/src/session/conversationShareProjection.ts
+++ b/apps/mobile/src/session/conversationShareProjection.ts
@@ -2,6 +2,7 @@ import {
parseChatQuoteSegments,
stripChatQuoteMarkerLines,
} from '@cindy/maker-shared/chat-quotes';
+import { slashCommandDisplayLabel } from '@cindy/maker-shared/composer-palette';
import {
type ConversationShareAttachment,
type ConversationShareBodyPart,
@@ -130,7 +131,7 @@ function projectBodyParts(
if (token.display) parts.push({ kind: 'pasted', label: token.display });
continue;
}
- if (token.text) parts.push({ kind: 'slash', label: token.text });
+ if (token.text) parts.push({ kind: 'slash', label: slashCommandDisplayLabel(token.text) });
}
return parts;
}
diff --git a/apps/mobile/src/session/messageActions.ts b/apps/mobile/src/session/messageActions.ts
index d56343e440..5e0260476c 100644
--- a/apps/mobile/src/session/messageActions.ts
+++ b/apps/mobile/src/session/messageActions.ts
@@ -1,5 +1,6 @@
import type { NormalizedRemoteMessage } from '@/session/messageNormalize';
import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
+import { projectSlashCommandsInText } from '@cindy/maker-shared/composer-palette';
import { formatCompactTokens } from '@cindy/maker-shared/usage-format';
import { i18n } from '@/i18n';
import {
@@ -25,9 +26,10 @@ type ClipboardNavigator = {
};
export function buildMobileMessageCopyText(message: NormalizedRemoteMessage): string {
+ const projectedBody = projectSlashCommandsInText(message.body, message.slashCommandRanges);
const body = message.quotesEncoded
- ? stripChatQuoteMarkerLines(message.body)
- : message.body;
+ ? stripChatQuoteMarkerLines(projectedBody)
+ : projectedBody;
const parts = [body];
if (message.secondaryBody) parts.push(message.secondaryBody);
const attachments = message.attachments?.map((item) => item.name).filter(Boolean) ?? [];
diff --git a/apps/mobile/src/session/sentMessageAtoms.ts b/apps/mobile/src/session/sentMessageAtoms.ts
index 343ddd326c..bbe0ccdcd7 100644
--- a/apps/mobile/src/session/sentMessageAtoms.ts
+++ b/apps/mobile/src/session/sentMessageAtoms.ts
@@ -3,6 +3,7 @@ import {
type ChatQuote,
type ChatQuoteSegment,
} from '@cindy/maker-shared/chat-quotes';
+import { slashCommandDisplayLabel } from '@cindy/maker-shared/composer-palette';
export interface SentPastedTextRange {
start: number;
@@ -178,7 +179,11 @@ export function sentInlineTokensDisplayText(tokens: readonly SentInlineToken[]):
if (!display.endsWith('\n')) display += '\n';
continue;
}
- display += token.kind === 'pasted' ? token.display : token.text;
+ display += token.kind === 'pasted'
+ ? token.display
+ : token.kind === 'slash'
+ ? slashCommandDisplayLabel(token.text)
+ : token.text;
}
return display.trimEnd();
}
diff --git a/packages/maker-shared/src/__tests__/composerPalette.test.ts b/packages/maker-shared/src/__tests__/composerPalette.test.ts
index 483db89748..da9a815c27 100644
--- a/packages/maker-shared/src/__tests__/composerPalette.test.ts
+++ b/packages/maker-shared/src/__tests__/composerPalette.test.ts
@@ -3,10 +3,17 @@ import {
detectComposerTrigger,
filterAtResources,
filterSlashCommands,
+ findSlashCommandToken,
insertAtResource,
insertSlashCommand,
+ leadingSlashCommandRange,
+ leadingSlashInvocation,
mergeSlashCommands,
+ projectSlashCommandsInText,
+ restoreSlashCommandRuntimeAlias,
serializeAtResource,
+ slashCommandDisplayLabel,
+ slashCommandRuntimePrefixLength,
} from '../composerPalette.js';
describe('shared composer palette model', () => {
@@ -98,4 +105,107 @@ describe('shared composer palette model', () => {
expect(serializeAtResource({ type: 'file', name: 'design notes.md', relPath: 'docs/design notes.md' }))
.toBe('@"docs/design notes.md"');
});
+
+ it('projects Pi runtime /skill: aliases to the human slash label', () => {
+ expect(slashCommandDisplayLabel('/skill:git')).toBe('/git');
+ expect(slashCommandDisplayLabel('/git')).toBe('/git');
+ expect(slashCommandDisplayLabel('/compact')).toBe('/compact');
+ expect(projectSlashCommandsInText('/skill:git follow-up')).toBe('/skill:git follow-up');
+ expect(projectSlashCommandsInText('/skill:git follow-up', [{ start: 0, end: 10 }])).toBe(
+ '/git follow-up',
+ );
+ expect(
+ restoreSlashCommandRuntimeAlias(
+ '/skill:git follow-up',
+ '/git please review',
+ [{ start: 0, end: 10 }],
+ ),
+ ).toBe('/skill:git please review');
+ expect(restoreSlashCommandRuntimeAlias('/skill:git follow-up', '/git please review')).toBe(
+ '/git please review',
+ );
+ expect(
+ restoreSlashCommandRuntimeAlias('/skill:git follow-up', '/help', [{ start: 0, end: 10 }]),
+ ).toBe('/help');
+ const quotedOriginal = '> quoted\n\n/skill:git follow-up';
+ const quotedSkillStart = quotedOriginal.indexOf('/skill:git');
+ expect(
+ restoreSlashCommandRuntimeAlias(
+ quotedOriginal,
+ '> quoted\n\n/git please',
+ [{ start: quotedSkillStart, end: quotedSkillStart + 10 }],
+ ),
+ ).toBe('> quoted\n\n/skill:git please');
+ const mixed = '/skill:unknown\n/help later';
+ const helpStart = mixed.indexOf('/help');
+ expect(
+ restoreSlashCommandRuntimeAlias(
+ mixed,
+ '/unknown\n/help later',
+ [{ start: helpStart, end: helpStart + 5 }],
+ ),
+ ).toBe('/unknown\n/help later');
+ expect(findSlashCommandToken(' /skill:git old')).toEqual({
+ start: 2,
+ end: 12,
+ name: 'skill:git',
+ });
+ expect(
+ restoreSlashCommandRuntimeAlias(
+ ' /skill:git old',
+ ' /git new',
+ [{ start: 2, end: 12 }],
+ ),
+ ).toBe(' /skill:git new');
+ const wireQuote = [
+ '> <!-- cindy-composer-quote -->',
+ '> quoted',
+ '',
+ '/skill:git follow-up',
+ ].join('\n');
+ const wireSkillStart = wireQuote.indexOf('/skill:git');
+ expect(
+ restoreSlashCommandRuntimeAlias(
+ wireQuote,
+ 'quoted\n\n/git please',
+ [{ start: wireSkillStart, end: wireSkillStart + 10 }],
+ ),
+ ).toBe('quoted\n\n/skill:git please');
+ expect(leadingSlashCommandRange('/skill:git please review')).toEqual({ start: 0, end: 10 });
+ const quotedRuntime = '> quoted\n\n/skill:git please';
+ const quotedRuntimeStart = quotedRuntime.indexOf('/skill:git');
+ expect(leadingSlashCommandRange(quotedRuntime)).toEqual({
+ start: quotedRuntimeStart,
+ end: quotedRuntimeStart + 10,
+ });
+ expect(leadingSlashInvocation(' \n/git please')).toEqual({
+ start: 3,
+ end: 7,
+ name: 'git',
+ });
+ expect(leadingSlashInvocation('please /git')).toBeUndefined();
+ expect(leadingSlashInvocation('> quoted\n\n/git')).toBeUndefined();
+ const quoted = [
+ '> <!-- cindy-composer-quote -->',
+ '> quoted',
+ '',
+ '/skill:git follow-up',
+ ].join('\n');
+ const skillStart = quoted.indexOf('/skill:git');
+ expect(
+ projectSlashCommandsInText(quoted, [{ start: skillStart, end: skillStart + 10 }]),
+ ).toContain('/git follow-up');
+ expect(
+ slashCommandRuntimePrefixLength('/skill:git', {
+ name: 'git',
+ runtimeCommandName: 'skill:git',
+ }),
+ ).toBe(6);
+ expect(
+ slashCommandRuntimePrefixLength('/git', {
+ name: 'git',
+ runtimeCommandName: 'skill:git',
+ }),
+ ).toBe(0);
+ });
});
diff --git a/packages/maker-shared/src/composerPalette.ts b/packages/maker-shared/src/composerPalette.ts
index 9638b93099..b8d7bc62e3 100644
--- a/packages/maker-shared/src/composerPalette.ts
+++ b/packages/maker-shared/src/composerPalette.ts
@@ -97,6 +97,113 @@ export function insertSlashCommand(
return `${text.slice(0, trigger.from)}/${command.name} `;
}
+/** Pi runtime invocation is `/skill:name`. Display layer always shows `/name`. */
+const PI_SKILL_RUNTIME_TOKEN_RE = /^\/skill:(\S+)$/i;
+const PI_SKILL_RUNTIME_PREFIX = 'skill:';
+
+/** Project a stored slash token (`/skill:git` or `/git`) to the human label. */
+export function slashCommandDisplayLabel(commandText: string): string {
+ const match = commandText.match(PI_SKILL_RUNTIME_TOKEN_RE);
+ return match ? `/${match[1]}` : commandText;
+}
+
+/**
+ * Project confirmed slash runs in a message body to the human label.
+ * Without ranges, leave the text untouched — ordinary `/skill:foo` prose
+ * must not be rewritten.
+ */
+export function projectSlashCommandsInText(
+ text: string,
+ ranges?: readonly { start: number; end: number }[],
+): string {
+ if (!ranges || ranges.length === 0) return text;
+ let result = text;
+ const ordered = [...ranges].sort((a, b) => b.start - a.start);
+ for (const range of ordered) {
+ if (range.start < 0 || range.end > result.length || range.end <= range.start) continue;
+ const token = result.slice(range.start, range.end);
+ const display = slashCommandDisplayLabel(token);
+ if (display === token) continue;
+ result = `${result.slice(0, range.start)}${display}${result.slice(range.end)}`;
+ }
+ return result;
+}
+
+/**
+ * Put a displayed `/git ...` back to the stored `/skill:git ...` when the
+ * user is resending an edited Pi skill message. Leave other commands alone.
+ */
+export function findSlashCommandToken(
+ text: string,
+): { start: number; end: number; name: string } | undefined {
+ const match = /(?:^|\n)[^\S\n]*(\/\S+)/.exec(text);
+ if (!match || match.index === undefined) return undefined;
+ const start = match.index + match[0].length - match[1].length;
+ return { start, end: start + match[1].length, name: match[1].slice(1) };
+}
+
+/** True when a confirmed slash range covers this token. */
+export function slashCommandRangeCoversToken(
+ ranges: readonly { start: number; end: number }[] | undefined,
+ token: { start: number; end: number } | undefined,
+): boolean {
+ if (!ranges || !token) return false;
+ return ranges.some((range) => range.start <= token.start && range.end >= token.end);
+}
+
+export function restoreSlashCommandRuntimeAlias(
+ originalText: string,
+ editedText: string,
+ confirmedRanges?: readonly { start: number; end: number }[],
+): string {
+ const original = findSlashCommandToken(originalText);
+ const edited = findSlashCommandToken(editedText);
+ if (!original || !edited) return editedText;
+ if (!slashCommandRangeCoversToken(confirmedRanges, original)) return editedText;
+ if (!original.name.toLowerCase().startsWith(PI_SKILL_RUNTIME_PREFIX)) return editedText;
+ const humanName = original.name.slice(PI_SKILL_RUNTIME_PREFIX.length);
+ if (!humanName || edited.name.toLowerCase() !== humanName.toLowerCase()) return editedText;
+ return `${editedText.slice(0, edited.start)}/${original.name}${editedText.slice(edited.end)}`;
+}
+
+/** Range of the first `/command` token in already-restored submit text. */
+export function leadingSlashCommandRange(
+ text: string,
+): { start: number; end: number } | undefined {
+ const token = findSlashCommandToken(text);
+ return token ? { start: token.start, end: token.end } : undefined;
+}
+
+/**
+ * First `/token` after leading whitespace. Same recognition window as Pi
+ * (`text.trimStart().startsWith('/skill:')`): leading spaces/newlines count,
+ * a quote block or other prose before the slash does not.
+ */
+export function leadingSlashInvocation(
+ text: string,
+): { start: number; end: number; name: string } | undefined {
+ const start = text.search(/\S/);
+ if (start < 0 || text[start] !== '/') return undefined;
+ const token = text.slice(start).match(/^\/\S+/)?.[0];
+ if (!token) return undefined;
+ return { start, end: start + token.length, name: token.slice(1) };
+}
+
+/**
+ * Length of the hidden `skill:` run after `/` when the visible token is a Pi
+ * runtime alias. Zero when the document already uses the human name.
+ */
+export function slashCommandRuntimePrefixLength(
+ commandText: string,
+ command: { name?: string; runtimeCommandName?: string },
+): number {
+ const runtime = command.runtimeCommandName?.trim();
+ if (!runtime || !runtime.toLowerCase().startsWith(PI_SKILL_RUNTIME_PREFIX)) return 0;
+ const body = commandText.startsWith('/') ? commandText.slice(1) : commandText;
+ if (body.toLowerCase() !== runtime.toLowerCase()) return 0;
+ return PI_SKILL_RUNTIME_PREFIX.length;
+}
+
export function insertAtResource(
text: string,
trigger: ComposerTrigger,