Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(plugins): let plugins read and rewrite the composer draft

vastsa412102f01a28
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index 82edf676f..026378e53 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -27,9 +27,6 @@ import { composerModelDisplayName, sameComposerModelId } from "../lib/composer-m
import {
resolveComposerThinkingProvider,
} from "../lib/session-thinking";
-import {
- useComposerAutocomplete,
-} from "../hooks/use-composer-autocomplete";
import { ComposerAutocomplete } from "./ComposerAutocomplete";
import { AskToolCard } from "./AskToolCard";
import { PlanApprovalBar } from "./PlanApprovalBar";
@@ -44,17 +41,12 @@ import {
thinkingProviderForModel,
type ComposerPrefill,
} from "../features/chat/composer/model";
-import {
- createFileReference,
- editorSelectionRange,
- readEditorValue,
- setEditorCaret,
- isImageFilePath,
- nextChipToken,
-} from "../features/chat/composer/editor";
+import { editorSelectionRange } from "../features/chat/composer/editor";
import { useComposerAttachments } from "../features/chat/composer/hooks/useComposerAttachments";
+import { useComposerCompletions } from "../features/chat/composer/hooks/useComposerCompletions";
import { useComposerDraft } from "../features/chat/composer/hooks/useComposerDraft";
import { useComposerInputHistory } from "../features/chat/composer/hooks/useComposerInputHistory";
+import { usePluginComposerBridge } from "../features/chat/composer/hooks/usePluginComposerBridge";
import { useComposerSubmit } from "../features/chat/composer/hooks/useComposerSubmit";
import { ComposerImageAttachments } from "../features/chat/composer/ComposerImageAttachments";
import { ComposerInput } from "../features/chat/composer/ComposerInput";
@@ -64,7 +56,6 @@ import { VoiceOverlay } from "../features/voice/VoiceOverlay";
import "../styles/voice.css";
import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";
import { ComposerStatus } from "../features/chat/composer/ComposerStatus";
-import { registerComposerInsert } from "../features/chat/composer/insert-bridge";
const EMPTY_QUEUED_PROMPTS: QueuedPrompt[] = [];
@@ -475,63 +466,20 @@ export function Composer({
}
},
});
- const composerAc = useComposerAutocomplete({
+ const completions = useComposerCompletions({
value,
cursor,
composing,
enabled: !inputBlocked,
+ referenceSessionId,
+ fileReferencesRef,
+ applyEditorDraft,
+ handleInput,
+ invalidatePromptEnhancement,
});
- const acceptCompletion = (index: number) => {
- const result = composerAc.accept(index);
- if (!result) return;
- invalidatePromptEnhancement();
- // File accept strips the @ token (empty insert) and used to store a
- // token-less chip above the textarea. Inline chips only paint when a
- // sentinel is in the draft, so Enter looked like the reference vanished.
- const acceptedFileReference = result.fileReference;
- if (!acceptedFileReference) {
- applyEditorDraft(result.value, fileReferencesRef.current, result.cursor);
- return;
- }
- const token = nextChipToken();
- const nextText =
- result.value.slice(0, result.cursor) + token + result.value.slice(result.cursor);
- applyEditorDraft(
- nextText,
- [
- ...fileReferencesRef.current,
- createFileReference(
- acceptedFileReference.path,
- acceptedFileReference.name,
- referenceSessionId,
- {
- kind: isImageFilePath(acceptedFileReference.path) ? "image" : "file",
- token,
- },
- ),
- ],
- result.cursor + token.length,
- );
- };
-
- // The insert bridge: plugin slot components reach the draft through
- // `composer.insertText`; this composer instance owns the live route while
- // it is mounted and clears it on unmount (last-writer-wins is the docked
- // composer, which is the one the user sees).
- useEffect(() => {
- registerComposerInsert((text) => {
- const element = draft.ref.current;
- if (!element) return;
- const current = readEditorValue(element);
- const selection = editorSelectionRange(element);
- const nextText = current.slice(0, selection.start) + text + current.slice(selection.end);
- applyEditorDraft(nextText, fileReferencesRef.current, selection.start + text.length);
- element.focus();
- setEditorCaret(element, selection.start + text.length);
- });
- return () => registerComposerInsert(null);
- }, [draft, fileReferencesRef]);
+ // Plugin draft and attachment actions reach this composer while it takes input.
+ usePluginComposerBridge({ ...draft, inputBlocked });
// Keep the transcript's bottom reserve in sync with the composer's real
// height (it grows with multi-line input) so the last message sits just
@@ -604,8 +552,8 @@ export function Composer({
{inputFocused ? (
<ComposerAutocomplete
anchorRef={composerShellRef}
- ac={composerAc}
- onAccept={acceptCompletion}
+ ac={completions.ac}
+ onAccept={completions.acceptCompletion}
/>
) : null}
<ComposerInput
@@ -618,14 +566,13 @@ export function Composer({
pasting={pasting}
enterToSend={enterToSend}
runActive={runActive}
- composerAc={composerAc}
- onPaste={pasteClipboardFiles}
- onAcceptCompletion={acceptCompletion}
- onSubmit={(steering) => void submitFromComposer(steering)}
+ composerAc={completions.ac}
+ onAcceptCompletion={completions.acceptCompletion}
+ onSubmit={(steering) => void submit(steering)}
onInsertNewline={insertNewlineInEditor}
onInput={(source, caret) => {
inputHistory.exitBrowsing();
- handleInput(source, caret);
+ completions.handleInput(source, caret);
}}
onHistoryNavigate={inputHistory.navigate}
onCompositionStart={() => setComposing(true)}
diff --git a/apps/desktop/src/components/ComposerAutocomplete.tsx b/apps/desktop/src/components/ComposerAutocomplete.tsx
index 6c5bd4a9a..be391bc2a 100644
--- a/apps/desktop/src/components/ComposerAutocomplete.tsx
+++ b/apps/desktop/src/components/ComposerAutocomplete.tsx
@@ -1,7 +1,10 @@
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import type { ComposerCommand } from "@pi-desktop/shared";
-import type { AutocompleteItem, useComposerAutocomplete } from "../hooks/use-composer-autocomplete";
+import type {
+ CompletionController,
+ CompletionItem,
+} from "../features/chat/composer/hooks/useComposerCompletions";
import {
IconBookOpen,
IconFileText,
@@ -62,7 +65,7 @@ export function ComposerAutocomplete({
onAccept,
}: {
anchorRef: React.RefObject<HTMLElement | null>;
- ac: ReturnType<typeof useComposerAutocomplete>;
+ ac: CompletionController;
onAccept: (index: number) => void;
}) {
const { t } = useTranslation();
@@ -77,14 +80,16 @@ export function ComposerAutocomplete({
if (!ac.open) return null;
- const renderRow = (item: AutocompleteItem, index: number) => {
+ const renderRow = (item: CompletionItem, index: number) => {
const active = index === ac.highlight;
const rowClass = `composer-plus-item composer-ac-item ${active ? "kb-active" : ""}`;
const commonProps = {
key:
item.kind === "command"
? `c:${item.command.kind}:${item.command.name}`
- : `p:${item.entry.path}`,
+ : item.kind === "plugin"
+ ? `pl:${item.pluginId}:${index}`
+ : `p:${item.entry.path}`,
type: "button" as const,
role: "option" as const,
"aria-selected": active,
@@ -118,6 +123,17 @@ export function ComposerAutocomplete({
</button>
);
}
+ if (item.kind === "plugin") {
+ return (
+ <button {...commonProps} title={item.row.detail}>
+ <span className="composer-ac-icon">
+ <IconPlug size={14} />
+ </span>
+ <span className="composer-ac-name">{item.row.label}</span>
+ {item.row.detail ? <span className="composer-ac-desc">{item.row.detail}</span> : null}
+ </button>
+ );
+ }
const isDir = item.entry.kind === "dir";
const name = item.entry.path.split("/").pop() ?? item.entry.path;
const displayName = `${name}${isDir ? "/" : ""}`;
@@ -148,6 +164,14 @@ export function ComposerAutocomplete({
</div>,
);
}
+ } else if (item.kind === "plugin" && lastGroup !== `plugin:${item.pluginId}`) {
+ // A plugin's rows sit under its own name, after the host's.
+ lastGroup = `plugin:${item.pluginId}`;
+ rows.push(
+ <div key={`g:${lastGroup}`} className="composer-model-group-label">
+ {item.pluginName}
+ </div>,
+ );
}
rows.push(renderRow(item, index));
});
@@ -166,7 +190,13 @@ export function ComposerAutocomplete({
onClose={ac.close}
anchorRef={anchorRef}
menuClassName="composer-autocomplete"
- label={t(ac.mode === "file" ? "chat.fileMenu" : "chat.slashMenu")}
+ label={t(
+ ac.mode === "file"
+ ? "chat.fileMenu"
+ : ac.mode === "plugin"
+ ? "chat.pluginTriggerMenu"
+ : "chat.slashMenu",
+ )}
role="listbox"
side="top"
matchAnchorWidth
diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsx
index 2984cdc3f..f1f02b39d 100644
--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx
@@ -8,13 +8,11 @@ import type {
RefObject,
SetStateAction,
} from "react";
-import type { useComposerAutocomplete } from "../../../hooks/use-composer-autocomplete";
import { editorSelectionRange, readEditorValue } from "./editor";
import { ComposerImagePreview } from "./ComposerImagePreview";
+import type { CompletionController } from "./hooks/useComposerCompletions";
import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview";
-type AutocompleteController = ReturnType<typeof useComposerAutocomplete>;
-
export type ComposerInputProps = {
imagePreview?: ComposerImagePreviewController;
inputRef: RefObject<HTMLDivElement | null>;
@@ -25,7 +23,7 @@ export type ComposerInputProps = {
pasting: boolean;
enterToSend: boolean;
runActive: boolean;
- composerAc: AutocompleteController;
+ composerAc: CompletionController;
onPaste: (event: ClipboardEvent<HTMLDivElement>) => void;
onAcceptCompletion: (index: number) => void;
onSubmit: (steering?: boolean) => void;
diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.ts
index b3a8f0e79..d07c82364 100644
--- a/apps/desktop/src/features/chat/composer/editor.ts
+++ b/apps/desktop/src/features/chat/composer/editor.ts
@@ -2,6 +2,7 @@ import {
fileReferenceLabel,
formatFileInsert,
} from "@pi-desktop/shared";
+import type { ComposerPluginPart } from "../../../lib/composer-smart-stop";
import type { ComposerFileReference } from "./model";
export { type ComposerFileReference } from "./model";
@@ -41,6 +42,7 @@ export function createFileReference(
kind?: "image" | "file";
mimeType?: string;
token?: string;
+ plugin?: ComposerPluginPart;
},
): ComposerFileReference {
composerFileReferenceSequence += 1;
@@ -48,13 +50,21 @@ export function createFileReference(
id: `composer-file-${composerFileReferenceSequence}`,
sessionId,
path,
- name: fileReferenceLabel(path, preferredName),
+ // A plugin mark's label is shown as given; it is no path.
+ name: isPluginMark(metadata) ? (preferredName ?? "") : fileReferenceLabel(path, preferredName),
kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),
...(metadata?.mimeType ? { mimeType: metadata.mimeType } : {}),
...(metadata?.token ? { token: metadata.token } : {}),
+ ...(metadata?.plugin ? { plugin: metadata.plugin } : {}),
};
}
+/** A chip a plugin put in the draft that is text, not a file: a mark or the fold. */
+export function isPluginMark(reference: { plugin?: ComposerPluginPart } | undefined): boolean {
+ const kind = reference?.plugin?.kind;
+ return kind === "mark" || kind === "fold";
+}
+
const CHIP_TOKEN_BASE = 0xe000;
const CHIP_TOKEN_END = 0xf8ff;
let chipTokenSequence = 0;
@@ -235,9 +245,14 @@ const CHIP_ICON_SVG: Record<string, string> = {
'<path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"/><rect x="2" y="6" width="14" height="12" rx="2"/>',
file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
+ plugin:
+ '<path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>',
+ fold: '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
};
function chipIconKey(reference: ComposerFileReference): string {
+ if (reference.plugin?.kind === "mark") return "plugin";
+ if (reference.plugin?.kind === "fold") return "fold";
const mime = reference.mimeType ?? "";
if (reference.kind === "image" || mime.startsWith("image/")) return "image";
const name = reference.name;
@@ -256,6 +271,7 @@ function chipSvg(key: string, size = 13): string {
}
export function isEditableTextReference(reference: ComposerFileReference): boolean {
+ if (isPluginMark(reference)) return false;
return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);
}
@@ -276,11 +292,14 @@ function buildChipElement(
chip.className = "composer-chip";
chip.contentEditable = "false";
chip.dataset.token = token;
- chip.title = reference.path;
+ // A mark names the plugin that put it there where a file names its path.
+ const origin = isPluginMark(reference) ? (reference.plugin?.pluginId ?? "") : reference.path;
+ if (isPluginMark(reference)) chip.dataset.pluginMark = reference.plugin?.kind;
+ chip.title = origin;
const editableText = isEditableTextReference(reference);
const activate = editableText ? () => onExpandText(token) : undefined;
chip.setAttribute("role", activate ? "button" : "listitem");
- chip.setAttribute("aria-label", `${reference.name} — ${reference.path}`);
+ chip.setAttribute("aria-label", `${reference.name} — ${origin}`);
if (activate) {
chip.tabIndex = 0;
chip.dataset.action = "expand-text-reference";
@@ -328,7 +347,7 @@ export function paintEditorValue(
el: HTMLElement,
value: string,
referenceByToken: Map<string, ComposerFileReference>,
- removeLabelFor: (name: string) => string,
+ removeLabelFor: (reference: ComposerFileReference) => string,
onRemove: (token: string) => void,
onExpandText: (token: string) => void,
): void {
@@ -349,7 +368,7 @@ export function paintEditorValue(
buildChipElement(
reference,
char,
- removeLabelFor(reference.name),
+ removeLabelFor(reference),
onRemove,
onExpandText,
),
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
index 6fd3e5fd7..792b22876 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
@@ -10,6 +10,7 @@ import { api } from "../../../../lib/api";
import {
HOME_DRAFT_KEY,
deleteComposerDraft,
+ draftFileReference,
writeComposerDraft,
} from "../../../../lib/composer-draft-cache";
import {
@@ -139,7 +140,7 @@ export function useComposerAttachments({
text: nextText,
fileReferences: [
...previousReferences,
- ...chips.map((chip) => toDraftReference(chip.reference)),
+ ...chips.map((chip) => draftFileReference(chip.reference)),
],
});
const currentSessionId = useAppStore.getState().activeSessionId;
@@ -229,7 +230,7 @@ export function useComposerAttachments({
text: nextText,
fileReferences: [
...previousReferences,
- ...chips.map((chip) => toDraftReference(chip.reference)),
+ ...chips.map((chip) => draftFileReference(chip.reference)),
],
});
const currentSessionId = useAppStore.getState().activeSessionId;
@@ -343,7 +344,7 @@ export function useComposerAttachments({
text: nextText,
fileReferences: [
...previousReferences,
- ...chips.map((chip) => toDraftReference(chip.reference)),
+ ...chips.map((chip) => draftFileReference(chip.reference)),
],
});
const currentSessionId = useAppStore.getState().activeSessionId;
@@ -427,15 +428,6 @@ export function useComposerAttachments({
};
}
-function toDraftReference(reference: ComposerFileReference): ComposerDraftSnapshot["fileReferences"][number] {
- return {
- path: reference.path,
- name: reference.name,
- kind: reference.kind,
- ...(reference.mimeType ? { mimeType: reference.mimeType } : {}),
- ...(reference.token ? { token: reference.token } : {}),
- };
-}
function showToast(
t: TFunction,
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
new file mode 100644
index 000000000..e0da90c02
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
@@ -0,0 +1,233 @@
+/**
+ * The composer's completion list: the host's own `/` commands and `@` files
+ * (`useComposerAutocomplete`) followed by the group of the plugin owning the
+ * typed symbol (`composerTrigger`, `docs/plugin-plan/ui/composer/`), and
+ * what accepting a row does to the draft.
+ *
+ * A plugin trigger only answers the user's typing: it is off while an IME
+ * composes (the list freezes like the host's), while the input is blocked,
+ * and whenever the draft is not the text the user last typed, so a program's
+ * write never opens it. A provider that throws, rejects or takes too long
+ * collapses only its own group.
+ */
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type RefObject,
+} from "react";
+import {
+ useComposerAutocomplete,
+ type AutocompleteItem,
+} from "../../../../hooks/use-composer-autocomplete";
+import { slotRegistry } from "../../../../plugins/renderer-slots/registry";
+import { useAppStore } from "../../../../stores/app-store";
+import { createFileReference, isImageFilePath, nextChipToken } from "../editor";
+import type { ComposerFileReference } from "../model";
+import { placePluginMark } from "../plugins/plugin-marks";
+import {
+ askPluginTrigger,
+ detectPluginTrigger,
+ type PluginTriggerMatch,
+ type PluginTriggerRow,
+} from "../plugins/plugin-triggers";
+
+export type PluginCompletionItem = {
+ kind: "plugin";
+ pluginId: string;
+ /** The plugin's display name, the group's heading. */
+ pluginName: string;
+ row: PluginTriggerRow;
+};
+
+export type CompletionItem = AutocompleteItem | PluginCompletionItem;
+
+export type CompletionController = {
+ open: boolean;
+ /** The host's mode, or `plugin` when only a plugin's group is listed. */
+ mode: "slash" | "file" | "plugin" | null;
+ items: CompletionItem[];
+ hasItems: boolean;
+ highlight: number;
+ setHighlight: (index: number) => void;
+ truncated: boolean;
+ noWorkspace: boolean;
+ close: () => void;
+};
+
+type PluginAnswer = { key: string; rows: PluginTriggerRow[] | null };
+
+const NO_ITEMS: AutocompleteItem[] = [];
+
+export function useComposerCompletions({
+ value,
+ cursor,
+ composing,
+ enabled,
+ referenceSessionId,
+ fileReferencesRef,
+ applyEditorDraft,
+ handleInput,
+ invalidatePromptEnhancement,
+}: {
+ value: string;
+ cursor: number;
+ composing: boolean;
+ enabled: boolean;
+ referenceSessionId: string;
+ fileReferencesRef: RefObject<ComposerFileReference[]>;
+ applyEditorDraft: (text: string, references: ComposerFileReference[], caret: number) => void;
+ handleInput: (source: string, caret: number) => string;
+ invalidatePromptEnhancement: () => void;
+}) {
+ const host = useComposerAutocomplete({ value, cursor, composing, enabled });
+ const { triggers } = useSyncExternalStore(
+ slotRegistry.subscribe,
+ slotRegistry.getSnapshot,
+ slotRegistry.getSnapshot,
+ );
+ const plugins = useAppStore((state) => state.plugins);
+ const [typedValue, setTypedValue] = useState<string | null>(null);
+ const [answer, setAnswer] = useState<PluginAnswer | null>(null);
+ const [dismissedKey, setDismissedKey] = useState<string | null>(null);
+ const [highlight, setHighlight] = useState(0);
+ const frozenRef = useRef<PluginTriggerMatch | null>(null);
+
+ const liveMatch = useMemo(
+ () =>
+ enabled && value === typedValue
+ ? detectPluginTrigger(value, cursor, new Set(triggers.map((entry) => entry.trigger)))
+ : null,
+ [enabled, value, typedValue, cursor, triggers],
+ );
+ const match = composing ? frozenRef.current : liveMatch;
+ useEffect(() => {
+ if (!composing) frozenRef.current = liveMatch;
+ }, [composing, liveMatch]);
+
+ const entry = match ? triggers.find((candidate) => candidate.trigger === match.trigger) : undefined;
+ const tokenKey = entry && match ? `${entry.id}:${match.tokenStart}` : null;
+ const requestKey = tokenKey && match ? `${tokenKey}:${match.query}` : null;
+ const dismissed = tokenKey !== null && tokenKey === dismissedKey;
+
+ useEffect(() => {
+ if (dismissedKey && tokenKey !== dismissedKey) setDismissedKey(null);
+ }, [tokenKey, dismissedKey]);
+
+ useEffect(() => {
+ if (!entry || !match || !requestKey || dismissed) return;
+ let current = true;
+ void askPluginTrigger(entry.items, match, entry.pluginId).then((rows) => {
+ if (current) setAnswer({ key: requestKey, rows });
+ });
+ return () => {
+ current = false;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- requestKey names entry and match
+ }, [requestKey, dismissed]);
+
+ const pluginItems = useMemo<PluginCompletionItem[]>(() => {
+ if (!entry || dismissed || !answer || answer.key !== requestKey) return [];
+ const pluginName =
+ plugins.find((plugin) => plugin.id === entry.pluginId)?.name ?? entry.pluginId;
+ return (answer.rows ?? []).map((row) => ({
+ kind: "plugin",
+ pluginId: entry.pluginId,
+ pluginName,
+ row,
+ }));
+ }, [entry, dismissed, answer, requestKey, plugins]);
+
+ const hostItems = host.open ? host.items : NO_ITEMS;
+ const items = useMemo<CompletionItem[]>(
+ () => [...hostItems, ...pluginItems],
+ [hostItems, pluginItems],
+ );
+
+ // A new query restarts keyboard navigation at the top hit.
+ const itemsKey = `${host.mode}:${host.query}|${requestKey}`;
+ useEffect(() => {
+ setHighlight(0);
+ }, [itemsKey]);
+
+ const hostClose = host.close;
+ const close = useCallback(() => {
+ hostClose();
+ if (tokenKey) setDismissedKey(tokenKey);
+ }, [hostClose, tokenKey]);
+
+ const open = host.open || pluginItems.length > 0;
+ const ac: CompletionController = {
+ open,
+ mode: host.mode ?? (open ? "plugin" : null),
+ items,
+ hasItems: items.length > 0,
+ highlight: Math.min(highlight, Math.max(0, items.length - 1)),
+ setHighlight,
+ truncated: host.truncated,
+ noWorkspace: host.noWorkspace,
+ close,
+ };
+
+ const acceptCompletion = (index: number) => {
+ if (index >= hostItems.length) {
+ const item = pluginItems[index - hostItems.length];
+ if (!item || !match) return;
+ invalidatePromptEnhancement();
+ const text = value.slice(0, match.tokenStart) + value.slice(match.tokenEnd);
+ const placed = placePluginMark(
+ fileReferencesRef.current,
+ text,
+ { pluginId: item.pluginId, label: item.row.label, send: item.row.send },
+ referenceSessionId,
+ );
+ const token = placed.token ?? "";
+ applyEditorDraft(
+ text.slice(0, match.tokenStart) + token + text.slice(match.tokenStart),
+ placed.references,
+ match.tokenStart + token.length,
+ );
+ return;
+ }
+ const result = host.accept(index);
+ if (!result) return;
+ invalidatePromptEnhancement();
+ // File accept strips the @ token (empty insert) and used to store a
+ // token-less chip above the textarea. Inline chips only paint when a
+ // sentinel is in the draft, so Enter looked like the reference vanished.
+ const acceptedFileReference = result.fileReference;
+ if (!acceptedFileReference) {
+ applyEditorDraft(result.value, fileReferencesRef.current, result.cursor);
+ return;
+ }
+ const token = nextChipToken();
+ const nextText =
+ result.value.slice(0, result.cursor) + token + result.value.slice(result.cursor);
+ applyEditorDraft(
+ nextText,
+ [
+ ...fileReferencesRef.current,
+ createFileReference(
+ acceptedFileReference.path,
+ acceptedFileReference.name,
+ referenceSessionId,
+ {
+ kind: isImageFilePath(acceptedFileReference.path) ? "image" : "file",
+ token,
+ },
+ ),
+ ],
+ result.cursor + token.length,
+ );
+ };
+
+ /** The draft's input handler, noting what the user typed. */
+ const handleTypedInput = (source: string, caret: number) => {
+ setTypedValue(handleInput(source, caret));
+ };
+
+ return { ac, acceptCompletion, handleInput: handleTypedInput };
+}
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
index eb50e1988..96d79cc05 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
@@ -19,12 +19,14 @@ import {
HOME_DRAFT_KEY,
captureComposerDraft,
deleteComposerDraft,
+ draftFileReference,
draftKeyForSession,
draftOwnerSessionId,
flushScheduledHomeDraftAdopt,
pruneComposerDrafts,
readComposerDraft,
readComposerDraftRevision,
+ sameDraftFileReference,
snapshotComposerDraft,
writeComposerDraft,
markComposerDraftEdited,
@@ -34,6 +36,7 @@ import {
createFileReference,
isEditableTextReference,
isPersistedScratchReference,
+ isPluginMark,
paintEditorValue,
readEditorValue,
setEditorCaret,
@@ -76,10 +79,12 @@ export type ComposerDraftController = {
paintCurrentDraft: (element: HTMLElement, nextValue: string) => void;
commitEditorDom: () => void;
insertNewlineInEditor: () => void;
+ /** Set the draft; `focus` false leaves focus where it is (plugin writes). */
applyEditorDraft: (
nextText: string,
nextReferences: ComposerFileReference[],
caret: number,
+ focus?: boolean,
) => void;
snapshotReferences: (sourceSessionId: string) => ComposerDraftSnapshot["fileReferences"];
draftSnapshot: (text: string) => ComposerDraftSnapshot;
@@ -178,12 +183,8 @@ export function useComposerDraft({
const next = typeof action === "function" ? action(current) : action;
const currentOwned = current.filter((reference) => reference.sessionId === referenceSessionId);
const nextOwned = next.filter((reference) => reference.sessionId === referenceSessionId);
- const changed = currentOwned.length !== nextOwned.length || currentOwned.some((reference, index) => {
- const nextReference = nextOwned[index];
- return !nextReference || reference.path !== nextReference.path ||
- reference.name !== nextReference.name || reference.kind !== nextReference.kind ||
- reference.mimeType !== nextReference.mimeType || reference.token !== nextReference.token;
- });
+ const changed = currentOwned.length !== nextOwned.length || currentOwned.some((reference, index) =>
+ !sameDraftFileReference(reference, nextOwned[index]));
if (changed) markComposerDraftEdited(draftKeyRef.current);
fileReferencesRef.current = next;
setFileReferences(next);
@@ -258,7 +259,10 @@ export function useComposerDraft({
element,
nextValue,
referenceByTokenRef.current,
- (name) => t("chat.removeFileReference", { name }),
+ (reference) =>
+ t(isPluginMark(reference) ? "chat.removePluginMark" : "chat.removeFileReference", {
+ name: reference.name,
+ }),
(token) => removeChipByTokenRef.current(token),
(token) => expandTextReferenceRef.current(token),
);
@@ -460,14 +464,15 @@ export function useComposerDraft({
if (previousWorkspacePathRef.current === workspacePath) return;
previousWorkspacePathRef.current = workspacePath;
const current = fileReferencesRef.current;
- const kept = current.filter((fileReference) =>
- isPersistedScratchReference(fileReference.path),
- );
+ // Plugin marks carry their text, not a workspace path.
+ const survives = (fileReference: ComposerFileReference) =>
+ Boolean(fileReference.plugin) || isPersistedScratchReference(fileReference.path);
+ const kept = current.filter(survives);
if (kept.length === current.length) return;
markComposerDraftEdited(draftKeyRef.current);
const droppedTokens = new Set(
current
- .filter((fileReference) => !isPersistedScratchReference(fileReference.path))
+ .filter((fileReference) => !survives(fileReference))
.flatMap((fileReference) =>
fileReference.token ? [fileReference.token] : [],
),
@@ -533,6 +538,7 @@ export function useComposerDraft({
nextText: string,
nextReferences: ComposerFileReference[],
caret: number,
+ focus = true,
) => {
const detached = detachImageTokens(nextText, nextReferences, caret);
nextText = detached.text;
@@ -541,10 +547,13 @@ export function useComposerDraft({
markComposerDraftEdited(draftKeyRef.current);
// A token may now refer to a different attachment even when text is equal.
editorValueRef.current = null;
- pendingEditorCaretRef.current = caret;
+ // A caret placed in an unfocused editor would focus it, so a write that
+ // leaves focus alone places none.
+ pendingEditorCaretRef.current = focus || document.activeElement === ref.current ? caret : null;
setValue(nextText);
setCursor(caret);
setFileReferences(nextReferences);
+ if (!focus) return;
requestAnimationFrame(() => {
const element = ref.current;
if (!element) return;
@@ -605,13 +614,7 @@ export function useComposerDraft({
const snapshotReferences = (sourceSessionId: string) =>
fileReferencesRef.current
.filter((fileReference) => fileReference.sessionId === sourceSessionId)
- .map(({ path, name, kind, mimeType, token }) => ({
- path,
- name,
- kind,
- ...(mimeType ? { mimeType } : {}),
- ...(token ? { token } : {}),
- }));
+ .map(draftFileReference);
const clearDraftForKey = (
key: string,
@@ -628,12 +631,8 @@ export function useComposerDraft({
: readComposerDraft(key);
if (!current || current.text.trim() !== submitted.text ||
current.fileReferences.length !== submitted.fileReferences.length ||
- current.fileReferences.some((reference, index) => {
- const expected = submitted.fileReferences[index];
- return reference.path !== expected.path || reference.name !== expected.name ||
- reference.kind !== expected.kind || reference.mimeType !== expected.mimeType ||
- reference.token !== expected.token;
- })) return;
+ current.fileReferences.some((reference, index) =>
+ !sameDraftFileReference(reference, submitted.fileReferences[index]))) return;
}
invalidatePromptEnhancement();
deleteComposerDraft(key);
@@ -682,13 +681,7 @@ export function useComposerDraft({
(fileReference) =>
!fileReference.token || text.includes(fileReference.token),
)
- .map(({ path, name, kind, mimeType, token }) => ({
- path,
- name,
- kind,
- ...(mimeType ? { mimeType } : {}),
- ...(token ? { token } : {}),
- })),
+ .map(draftFileReference),
});
return {
diff --git a/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts b/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts
new file mode 100644
index 000000000..1e95169ff
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts
@@ -0,0 +1,82 @@
+/**
+ * Lends this composer to the plugin draft bridge (`../plugins/draft-bridge.ts`)
+ * while it is mounted, and tells the bridge after every render that changed
+ * the draft, so plugin subscribers and the draft's generation follow it.
+ */
+import { useEffect, useRef, type RefObject } from "react";
+import { api } from "../../../../lib/api";
+import { editorSelectionRange, readEditorValue } from "../editor";
+import type { ComposerFileReference } from "../model";
+import { composerDraftBridge, type ComposerDraftHandle } from "../plugins/draft-bridge";
+
+type BridgeSource = {
+ ref: RefObject<HTMLDivElement | null>;
+ draftKey: string;
+ referenceSessionId: string;
+ value: string;
+ valueRef: { current: string };
+ fileReferences: ComposerFileReference[];
+ fileReferencesRef: { current: ComposerFileReference[] };
+ inputBlocked: boolean;
+ applyEditorDraft: (
+ text: string,
+ references: ComposerFileReference[],
+ caret: number,
+ focus?: boolean,
+ ) => void;
+};
+
+export function usePluginComposerBridge(source: BridgeSource): void {
+ const latest = useRef(source);
+ latest.current = source;
+ const handleRef = useRef<ComposerDraftHandle | null>(null);
+
+ useEffect(() => {
+ const text = () => {
+ const { ref, valueRef } = latest.current;
+ return ref.current ? readEditorValue(ref.current) : valueRef.current;
+ };
+ const handle: ComposerDraftHandle = {
+ read() {
+ const { inputBlocked, draftKey, referenceSessionId, fileReferencesRef } = latest.current;
+ if (inputBlocked) return null;
+ return {
+ draftKey,
+ sessionId: referenceSessionId,
+ text: text(),
+ references: fileReferencesRef.current,
+ };
+ },
+ focused() {
+ const element = latest.current.ref.current;
+ return element !== null && document.activeElement === element;
+ },
+ selection() {
+ const element = latest.current.ref.current;
+ if (element) return editorSelectionRange(element);
+ const end = text().length;
+ return { start: end, end };
+ },
+ write(nextText, references, caret, focus) {
+ latest.current.applyEditorDraft(nextText, references, caret, focus);
+ },
+ async stage(sessionId, file) {
+ const result = await api.pasteFiles(sessionId, [file]);
+ const staged = result.files[0];
+ if (!staged) throw new Error("the host staged no file");
+ return staged;
+ },
+ };
+ handleRef.current = handle;
+ const unregister = composerDraftBridge.register(handle);
+ return () => {
+ handleRef.current = null;
+ unregister();
+ };
+ }, []);
+
+ const { value, fileReferences, draftKey, referenceSessionId, inputBlocked } = source;
+ useEffect(() => {
+ if (handleRef.current) composerDraftBridge.publish(handleRef.current);
+ }, [value, fileReferences, draftKey, referenceSessionId, inputBlocked]);
+}
diff --git a/apps/desktop/src/features/chat/composer/insert-bridge.ts b/apps/desktop/src/features/chat/composer/insert-bridge.ts
deleted file mode 100644
index b302000f4..000000000
--- a/apps/desktop/src/features/chat/composer/insert-bridge.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Renderer-internal bridge for the `composer.insertText` outbound action.
- *
- * The composer is renderer-local, so the dispatch relay routes that action
- * here instead of through the main process. The composer registers its
- * insertion implementation on mount and clears it on unmount; with no
- * composer mounted the relay answers `PLUGIN_ACTION_NO_COMPOSER`.
- */
-
-type ComposerInsert = (text: string) => void;
-
-let handler: ComposerInsert | null = null;
-
-/** Called by the composer when it can accept draft insertions. */
-export function registerComposerInsert(fn: ComposerInsert | null): void {
- handler = fn;
-}
-
-/** Returns false when no composer is mounted to receive the text. */
-export function insertComposerText(text: string): boolean {
- if (!handler) return false;
- handler(text);
- return true;
-}
-
-/** Test seam. */
-export function resetComposerInsertBridge(): void {
- handler = null;
-}
diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.ts
index ebb079b76..d0dfdec2b 100644
--- a/apps/desktop/src/features/chat/composer/model.ts
+++ b/apps/desktop/src/features/chat/composer/model.ts
@@ -11,8 +11,9 @@ import {
PERMISSION_MODES,
sessionThinkingMenuLevels,
} from "@pi-desktop/shared";
-import { sameComposerModelId } from "../../../lib/composer-models.ts";
-import { providerThinkingLevels } from "../../../lib/session-thinking.ts";
+import { sameComposerModelId } from "../../../lib/composer-models";
+import type { ComposerPluginPart } from "../../../lib/composer-smart-stop";
+import { providerThinkingLevels } from "../../../lib/session-thinking";
export const COMPOSER_MIN_HEIGHT_PX = 28;
export const COMPOSER_MAX_VISIBLE_ROWS = 7;
@@ -63,6 +64,7 @@ export type ComposerFileReference = {
kind: "image" | "file";
mimeType?: string;
token?: string;
+ plugin?: ComposerPluginPart;
};
export type ComposerMenuView = "root" | "model";
diff --git a/apps/desktop/src/features/chat/composer/plugins/draft-bridge.ts b/apps/desktop/src/features/chat/composer/plugins/draft-bridge.ts
new file mode 100644
index 000000000..ce1476c3b
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/plugins/draft-bridge.ts
@@ -0,0 +1,275 @@
+/**
+ * The composer end of the plugin draft and attachment actions
+ * (`docs/plugin-plan/render/draft/`, `docs/plugin-plan/render/attachments/`).
+ *
+ * A composer taking input registers a handle; the last one registered is the
+ * one plugins reach, so a composer that mounts over another takes over until
+ * it unmounts. The bridge owns the draft's generation: one counter for the
+ * whole window, moved on by every change of the draft the handle shows,
+ * including a switch to another session's draft, so `expectedGeneration`
+ * compares across switches too.
+ *
+ * A write reaches the composer's state at once but its DOM only on the next
+ * render, so until the composer publishes that render, the bridge reads the
+ * draft it wrote instead of the handle's.
+ */
+import {
+ PLUGIN_ATTACHMENTS_MAX,
+ type PluginAttachment,
+ type PluginDraftListener,
+ type PluginDraftSnapshot,
+ type PluginDraftWriteResult,
+ type PluginRendererErrorCode,
+} from "@pi-desktop/plugin-sdk";
+import type { ComposerPasteFile, ComposerPastedFile } from "@pi-desktop/shared";
+import { PluginRendererError } from "../../../../plugins/renderer-error";
+import { createFileReference, nextChipToken } from "../editor";
+import type { ComposerFileReference } from "../model";
+import {
+ draftReferences,
+ draftSignature,
+ holdsDraftChip,
+ planDraftReplacement,
+ pluginDraftView,
+ type DraftMarkInput,
+ type LiveDraft,
+} from "./plugin-draft";
+
+/** What a composer lends the bridge while it takes input. */
+export type ComposerDraftHandle = {
+ /** The draft as the composer holds it, or `null` while input is blocked. */
+ read(): LiveDraft | null;
+ /** Whether the user is in the composer's input. */
+ focused(): boolean;
+ /** The selection in the draft text; the end of it when outside. */
+ selection(): { start: number; end: number };
+ /** Set the draft; `focus` also moves focus into the input. */
+ write(text: string, references: ComposerFileReference[], caret: number, focus: boolean): void;
+ /** Keep a file in the session's scratch space for the next message. */
+ stage(sessionId: string, file: ComposerPasteFile): Promise<ComposerPastedFile>;
+};
+
+/** `composer.replaceDraft`, its shape checked. */
+export type DraftReplaceInput = {
+ readonly expectedGeneration: number;
+ readonly text: string;
+ readonly marks: readonly DraftMarkInput[];
+};
+
+/** `attachments.add`, its shape and limits checked. */
+export type AttachmentInput = {
+ readonly name: string;
+ readonly mimeType: string;
+ readonly data: ArrayBuffer;
+};
+
+type Live = { readonly handle: ComposerDraftHandle; readonly draft: LiveDraft };
+type Subscriber = { readonly pluginId: string; readonly listener: PluginDraftListener };
+
+function refuse(code: PluginRendererErrorCode, message: string): never {
+ throw new PluginRendererError(code, message);
+}
+
+/** `pluginId`'s attachments in the draft, the detached images included. */
+function ownAttachments(draft: LiveDraft, pluginId: string): ComposerFileReference[] {
+ return draftReferences(draft).filter(
+ (reference) =>
+ reference.plugin?.kind === "attachment" &&
+ reference.plugin.pluginId === pluginId &&
+ (!reference.token || draft.text.includes(reference.token)),
+ );
+}
+
+export class ComposerDraftBridge {
+ private readonly handles: ComposerDraftHandle[] = [];
+ private readonly subscribers = new Set<Subscriber>();
+ private pending: (Live & { readonly caret: number }) | null = null;
+ private signature = "";
+ private generation = 0;
+ private readonly warn: (message: string, error: unknown) => void;
+
+ constructor(warn: (message: string, error: unknown) => void = (message, error) => console.warn(message, error)) {
+ this.warn = warn;
+ }
+
+ /** Lend the bridge a composer; the returned call takes it back. */
+ register(handle: ComposerDraftHandle): () => void {
+ this.handles.push(handle);
+ this.sync();
+ return () => {
+ const index = this.handles.lastIndexOf(handle);
+ if (index === -1) return;
+ this.handles.splice(index, 1);
+ if (this.pending?.handle === handle) this.pending = null;
+ this.sync();
+ };
+ }
+
+ /** The composer's word that it rendered a change of its draft. */
+ publish(handle: ComposerDraftHandle): void {
+ if (this.pending?.handle === handle) this.pending = null;
+ this.sync();
+ }
+
+ subscribe(pluginId: string, listener: PluginDraftListener): () => void {
+ const subscriber: Subscriber = { pluginId, listener };
+ const live = this.sync();
+ this.subscribers.add(subscriber);
+ this.notify(subscriber, live);
+ return () => {
+ this.subscribers.delete(subscriber);
+ };
+ }
+
+ readDraft(pluginId: string): PluginDraftSnapshot {
+ return this.snapshot(this.require().draft, pluginId);
+ }
+
+ /** Put plain text at the caret, replacing the selection, and focus the input. */
+ insertText(text: string): PluginDraftWriteResult {
+ const { handle, draft } = this.require();
+ if (holdsDraftChip(draft, text)) {
+ refuse("PLUGIN_ACTION_INVALID_PAYLOAD", "the text holds a chip token of the draft");
+ }
+ const pending = this.pending?.handle === handle ? this.pending : null;
+ const { start, end } = pending ? { start: pending.caret, end: pending.caret } : handle.selection();
+ const next = draft.text.slice(0, start) + text + draft.text.slice(end);
+ return this.commit({ handle, draft }, next, [...draft.references], start + text.length, true);
+ }
+
+ /**
+ * Replace the whole draft. The gates run in this order and a refusal
+ * writes nothing: a composer takes input, the call runs in a user's input
+ * event, the input does not have focus, the generation is current, the
+ * marks are the draft's and keep every host chip.
+ */
+ replaceDraft(pluginId: string, input: DraftReplaceInput, userGesture: boolean): PluginDraftWriteResult {
+ const live = this.require();
+ if (!userGesture) {
+ refuse("PLUGIN_DRAFT_REMOTE", "composer.replaceDraft runs only inside a user's input event");
+ }
+ if (live.handle.focused()) {
+ refuse("PLUGIN_DRAFT_FOCUSED", "the composer has focus; use composer.insertText");
+ }
+ if (input.expectedGeneration !== this.generation) {
+ refuse("PLUGIN_DRAFT_STALE", `the draft is at generation ${this.generation}`);
+ }
+ const plan = planDraftReplacement(live.draft, pluginId, input.text, input.marks);
+ if ("code" in plan) refuse(plan.code, plan.message);
+ return this.commit(live, plan.text, plan.references, plan.text.length, false);
+ }
+
+ listAttachments(pluginId: string): PluginAttachment[] {
+ return ownAttachments(this.require().draft, pluginId).map((reference) => ({
+ id: reference.plugin?.kind === "attachment" ? reference.plugin.id : "",
+ name: reference.name,
+ mimeType: reference.mimeType ?? "application/octet-stream",
+ size: reference.plugin?.kind === "attachment" ? reference.plugin.size : 0,
+ }));
+ }
+
+ /**
+ * Stage `input` for the next message of the session whose draft the
+ * composer shows now. An image goes with the draft's images; any other
+ * file is a chip at the end of the text. Neither moves focus.
+ */
+ async addAttachment(pluginId: string, input: AttachmentInput): Promise<{ id: string }> {
+ const { handle, draft } = this.require();
+ const sessionId = draft.sessionId;
+ if (!sessionId) refuse("PLUGIN_ATTACHMENT_NO_SESSION", "home has no session to take a file");
+ this.assertRoom(draft, pluginId);
+ let staged: ComposerPastedFile;
+ try {
+ staged = await handle.stage(sessionId, { name: input.name, mimeType: input.mimeType, data: input.data });
+ } catch (error) {
+ refuse("PLUGIN_ATTACHMENT_FAILED", error instanceof Error ? error.message : String(error));
+ }
+ const live = this.sync();
+ if (!live || live.draft.sessionId !== sessionId) {
+ refuse("PLUGIN_ATTACHMENT_NO_SESSION", "the session changed before the file was staged");
+ }
+ this.assertRoom(live.draft, pluginId);
+ const id = crypto.randomUUID();
+ const token = staged.kind === "image" ? undefined : nextChipToken();
+ const reference = createFileReference(staged.path, staged.name, sessionId, {
+ kind: staged.kind,
+ mimeType: staged.mimeType,
+ token,
+ plugin: { kind: "attachment", pluginId, id, size: staged.size },
+ });
+ const text = live.draft.text + (token ?? "");
+ this.commit(live, text, [...live.draft.references, reference], text.length, false);
+ return { id };
+ }
+
+ removeAttachment(pluginId: string, id: string): { ok: true } {
+ const live = this.require();
+ const target = ownAttachments(live.draft, pluginId).find(
+ (reference) => reference.plugin?.kind === "attachment" && reference.plugin.id === id,
+ );
+ if (!target) refuse("PLUGIN_ATTACHMENT_NOT_FOUND", `${pluginId} has no attachment ${JSON.stringify(id)}`);
+ const text = target.token ? live.draft.text.split(target.token).join("") : live.draft.text;
+ const references = live.draft.references.filter((reference) => reference !== target);
+ this.commit(live, text, references, text.length, false);
+ return { ok: true };
+ }
+
+ private assertRoom(draft: LiveDraft, pluginId: string): void {
+ if (ownAttachments(draft, pluginId).length >= PLUGIN_ATTACHMENTS_MAX) {
+ refuse("PLUGIN_ATTACHMENT_LIMIT", `a plugin holds at most ${PLUGIN_ATTACHMENTS_MAX} attachments`);
+ }
+ }
+
+ /** The composer plugins reach and its draft, the bridge's own write first. */
+ private live(): Live | null {
+ const handle = this.handles.at(-1);
+ const read = handle?.read() ?? null;
+ if (!handle || !read) return null;
+ return { handle, draft: this.pending?.handle === handle ? this.pending.draft : read };
+ }
+
+ /** Bring the generation up to the live draft and tell subscribers of a change. */
+ private sync(): Live | null {
+ const live = this.live();
+ const signature = draftSignature(live?.draft ?? null);
+ if (signature !== this.signature) {
+ this.signature = signature;
+ this.generation += 1;
+ for (const subscriber of [...this.subscribers]) this.notify(subscriber, live);
+ }
+ return live;
+ }
+
+ private require(): Live {
+ return this.sync() ?? refuse("PLUGIN_ACTION_NO_COMPOSER", "no composer takes input");
+ }
+
+ private commit(
+ live: Live,
+ text: string,
+ references: ComposerFileReference[],
+ caret: number,
+ focus: boolean,
+ ): PluginDraftWriteResult {
+ live.handle.write(text, references, caret, focus);
+ this.pending = { handle: live.handle, draft: { ...live.draft, text, references }, caret };
+ this.sync();
+ return { ok: true, generation: this.generation };
+ }
+
+ private snapshot(draft: LiveDraft, pluginId: string): PluginDraftSnapshot {
+ return { ...pluginDraftView(draft, pluginId), generation: this.generation };
+ }
+
+ private notify(subscriber: Subscriber, live: Live | null): void {
+ if (!this.subscribers.has(subscriber)) return;
+ try {
+ subscriber.listener(live ? this.snapshot(live.draft, subscriber.pluginId) : null);
+ } catch (error) {
+ this.warn(`[plugin-renderer] ${subscriber.pluginId} draft listener failed`, error);
+ }
+ }
+}
+
+/** The app window's bridge. */
+export const composerDraftBridge = new ComposerDraftBridge();
diff --git a/apps/desktop/src/features/chat/composer/plugins/plugin-draft.ts b/apps/desktop/src/features/chat/composer/plugins/plugin-draft.ts
new file mode 100644
index 000000000..dff0bc2af
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/plugins/plugin-draft.ts
@@ -0,0 +1,174 @@
+/**
+ * The composer draft as plugins see and write it
+ * (`docs/plugin-plan/render/draft/`). Pure, so the bridge and logic tests
+ * share it.
+ *
+ * A plugin's view is the draft's text with every chip replaced by one
+ * `PLUGIN_DRAFT_MARK_CHAR`, matched in order by `marks`. A literal mark char
+ * the user typed reads as U+FFFD, so the view never has more mark chars than
+ * marks. Only the caller's own marks show their `send` text.
+ */
+import {
+ PLUGIN_DRAFT_MARK_CHAR,
+ PLUGIN_DRAFT_MAX_MARKS,
+ type PluginDraftMark,
+} from "@pi-desktop/plugin-sdk";
+import type { ComposerFileReference } from "../model";
+import { createPluginMark } from "./plugin-marks";
+
+/** The draft of the composer taking input, as its own state holds it. */
+export type LiveDraft = {
+ /** The composer draft cache key: the session's, or home's. */
+ readonly draftKey: string;
+ /** The owning session, `""` on home. */
+ readonly sessionId: string;
+ /** The draft text, chips as their tokens. */
+ readonly text: string;
+ /** Every reference the composer holds, other sessions' included. */
+ readonly references: readonly ComposerFileReference[];
+};
+
+/** A new mark or an existing chip, already checked against the mark limits. */
+export type DraftMarkInput = { readonly id: string } | { readonly label: string; readonly send: string };
+
+export type DraftReplacement = {
+ readonly text: string;
+ readonly references: ComposerFileReference[];
+};
+
+export type DraftRefusal = {
+ readonly code: "PLUGIN_ACTION_INVALID_PAYLOAD" | "PLUGIN_DRAFT_ANCHOR";
+ readonly message: string;
+};
+
+const REPLACEMENT_CHAR = "\uFFFD";
+
+/** The draft's own references: those of its session. */
+export function draftReferences(draft: LiveDraft): ComposerFileReference[] {
+ return draft.references.filter((reference) => reference.sessionId === draft.sessionId);
+}
+
+/** The draft's chips by token. */
+function chipsByToken(draft: LiveDraft): Map<string, ComposerFileReference> {
+ const chips = new Map<string, ComposerFileReference>();
+ for (const reference of draftReferences(draft)) {
+ if (reference.token && draft.text.includes(reference.token)) chips.set(reference.token, reference);
+ }
+ return chips;
+}
+
+/**
+ * What changes the draft's generation: the draft switching, its text, and
+ * any of its references, detached images and fold counts included.
+ */
+export function draftSignature(draft: LiveDraft | null): string {
+ if (!draft) return "";
+ const references = draftReferences(draft).map((reference) => [
+ reference.id,
+ reference.token ?? "",
+ reference.name,
+ reference.plugin?.kind === "fold" ? reference.plugin.count : 0,
+ ]);
+ return JSON.stringify([draft.draftKey, draft.text, references]);
+}
+
+function markOf(reference: ComposerFileReference, pluginId: string): PluginDraftMark {
+ const part = reference.plugin;
+ if (part?.kind === "mark") {
+ return {
+ id: reference.id,
+ kind: "plugin",
+ label: reference.name,
+ pluginId: part.pluginId,
+ ...(part.pluginId === pluginId ? { send: part.send } : {}),
+ };
+ }
+ if (part?.kind === "fold") {
+ return { id: reference.id, kind: "fold", label: reference.name, count: part.count };
+ }
+ return { id: reference.id, kind: "host", label: reference.name };
+}
+
+/** `pluginId`'s view of the draft. */
+export function pluginDraftView(
+ draft: LiveDraft,
+ pluginId: string,
+): { text: string; marks: PluginDraftMark[] } {
+ const chips = chipsByToken(draft);
+ const marks: PluginDraftMark[] = [];
+ let text = "";
+ for (const char of draft.text) {
+ const chip = chips.get(char);
+ if (chip) {
+ chips.delete(char);
+ marks.push(markOf(chip, pluginId));
+ text += PLUGIN_DRAFT_MARK_CHAR;
+ } else {
+ text += char === PLUGIN_DRAFT_MARK_CHAR ? REPLACEMENT_CHAR : char;
+ }
+ }
+ return { text, marks };
+}
+
+/** Whether `text` holds one of the draft's chip tokens. */
+export function holdsDraftChip(draft: LiveDraft, text: string): boolean {
+ for (const token of chipsByToken(draft).keys()) if (text.includes(token)) return true;
+ return false;
+}
+
+/**
+ * The draft `pluginId` asks for: `text` with its i-th mark char taken by
+ * `marks[i]`, an existing chip by id or a new mark of the caller. Refused
+ * when an id is not a chip of the draft or is used twice, when a host chip or
+ * the fold is left out (anchor), or when more than `PLUGIN_DRAFT_MAX_MARKS`
+ * plugin marks would show. References without a chip (detached images) and
+ * other sessions' references are kept as they are.
+ */
+export function planDraftReplacement(
+ draft: LiveDraft,
+ pluginId: string,
+ text: string,
+ marks: readonly DraftMarkInput[],
+): DraftReplacement | DraftRefusal {
+ const invalid = (message: string): DraftRefusal => ({
+ code: "PLUGIN_ACTION_INVALID_PAYLOAD",
+ message,
+ });
+ if (holdsDraftChip(draft, text)) return invalid("the text holds a chip token of the draft");
+ const chips = [...chipsByToken(draft).values()];
+ const byId = new Map(chips.map((chip) => [chip.id, chip]));
+ const placed: ComposerFileReference[] = [];
+ for (const input of marks) {
+ if ("id" in input) {
+ const chip = byId.get(input.id);
+ if (!chip) return invalid(`no mark ${JSON.stringify(input.id)} in the draft, or it is used twice`);
+ byId.delete(input.id);
+ placed.push(chip);
+ } else {
+ placed.push(createPluginMark({ pluginId, ...input }, draft.sessionId));
+ }
+ }
+ const dropped = [...byId.values()];
+ const anchor = dropped.find((chip) => chip.plugin?.kind !== "mark");
+ if (anchor) {
+ return {
+ code: "PLUGIN_DRAFT_ANCHOR",
+ message: `the replacement drops the host chip ${JSON.stringify(anchor.name)}`,
+ };
+ }
+ if (placed.filter((chip) => chip.plugin?.kind === "mark").length > PLUGIN_DRAFT_MAX_MARKS) {
+ return invalid(`a draft shows at most ${PLUGIN_DRAFT_MAX_MARKS} plugin marks`);
+ }
+ let index = 0;
+ let next = "";
+ for (const char of text) {
+ next += char === PLUGIN_DRAFT_MARK_CHAR ? (placed[index++]?.token ?? "") : char;
+ }
+ const replaced = new Set(chips.map((chip) => chip.id));
+ const kept = draft.references.filter(
+ (reference) => reference.sessionId !== draft.sessionId || !replaced.has(reference.id),
+ );
+ const created = placed.filter((chip) => !replaced.has(chip.id));
+ const reused = placed.filter((chip) => replaced.has(chip.id));
+ return { text: next, references: [...kept, ...reused, ...created] };
+}
diff --git a/apps/desktop/src/features/chat/composer/plugins/plugin-marks.ts b/apps/desktop/src/features/chat/composer/plugins/plugin-marks.ts
new file mode 100644
index 000000000..802ec566c
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/plugins/plugin-marks.ts
@@ -0,0 +1,99 @@
+/**
+ * Plugin marks in the composer draft (`docs/plugin-plan/ui/composer/`,
+ * `docs/plugin-plan/render/draft/`).
+ *
+ * A mark is an atomic chip backed by a composer file reference with a
+ * `plugin` part: it shows its label and sends its `send` text in its place.
+ * One draft shows at most `PLUGIN_DRAFT_MAX_MARKS` of them; every mark past
+ * that joins a single fold chip `⧉ +N` at the place of the first one, which
+ * sends all of their texts. The fold is the host's, so it survives whatever
+ * any single plugin does.
+ */
+import { PLUGIN_DRAFT_MAX_MARKS } from "@pi-desktop/plugin-sdk";
+import { createFileReference, isPluginMark, nextChipToken } from "../editor";
+import type { ComposerFileReference } from "../model";
+
+export type PluginMarkInput = {
+ readonly pluginId: string;
+ readonly label: string;
+ readonly send: string;
+};
+
+/** The fold chip's label for `count` folded marks. */
+export function foldLabel(count: number): string {
+ return `\u29C9 +${count}`;
+}
+
+/** References whose chip is in `text`, in the order their chips appear. */
+export function liveChipReferences<T extends { token?: string }>(
+ references: readonly T[],
+ text: string,
+): T[] {
+ const byToken = new Map<string, T>();
+ for (const reference of references) if (reference.token) byToken.set(reference.token, reference);
+ const live: T[] = [];
+ for (const char of Array.from(text)) {
+ const reference = byToken.get(char);
+ if (reference) {
+ live.push(reference);
+ byToken.delete(char);
+ }
+ }
+ return live;
+}
+
+/** A new mark reference with a fresh chip token. */
+export function createPluginMark(mark: PluginMarkInput, sessionId: string): ComposerFileReference {
+ return createFileReference("", mark.label, sessionId, {
+ kind: "file",
+ token: nextChipToken(),
+ plugin: { kind: "mark", pluginId: mark.pluginId, send: mark.send },
+ });
+}
+
+export type PluginMarkPlacement = {
+ /** The session's references with the mark in them. */
+ readonly references: ComposerFileReference[];
+ /**
+ * The chip token to put where the mark goes, or `null` when the mark joined
+ * the fold already in the draft and nothing new goes into the text.
+ */
+ readonly token: string | null;
+};
+
+/**
+ * Add a mark to a draft whose text is `text` and whose references are
+ * `references` (one session's). Under the limit the mark is a chip of its
+ * own; at the limit it opens the fold, past it it joins the fold.
+ */
+export function placePluginMark(
+ references: readonly ComposerFileReference[],
+ text: string,
+ mark: PluginMarkInput,
+ sessionId: string,
+): PluginMarkPlacement {
+ const live = liveChipReferences(references, text).filter(isPluginMark);
+ const fold = live.find((reference) => reference.plugin?.kind === "fold");
+ if (fold?.plugin?.kind === "fold") {
+ const count = fold.plugin.count + 1;
+ const joined: ComposerFileReference = {
+ ...fold,
+ name: foldLabel(count),
+ plugin: { ...fold.plugin, count, send: `${fold.plugin.send} ${mark.send}` },
+ };
+ return {
+ references: references.map((reference) => (reference === fold ? joined : reference)),
+ token: null,
+ };
+ }
+ if (live.length < PLUGIN_DRAFT_MAX_MARKS) {
+ const created = createPluginMark(mark, sessionId);
+ return { references: [...references, created], token: created.token ?? null };
+ }
+ const opened = createFileReference("", foldLabel(1), sessionId, {
+ kind: "file",
+ token: nextChipToken(),
+ plugin: { kind: "fold", pluginId: mark.pluginId, send: mark.send, count: 1 },
+ });
+ return { references: [...references, opened], token: opened.token ?? null };
+}
diff --git a/apps/desktop/src/features/chat/composer/plugins/plugin-triggers.ts b/apps/desktop/src/features/chat/composer/plugins/plugin-triggers.ts
new file mode 100644
index 000000000..dab2057f8
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/plugins/plugin-triggers.ts
@@ -0,0 +1,137 @@
+/**
+ * Plugin-owned composer triggers (`docs/plugin-plan/ui/composer/`): where a
+ * trigger is active in the draft, and what of a plugin's answer the host
+ * keeps. Pure, so the completion hook and logic tests share it.
+ */
+import {
+ PLUGIN_MARK_LABEL_MAX_CHARS,
+ PLUGIN_MARK_SEND_MAX_BYTES,
+ PLUGIN_TRIGGER_DETAIL_MAX_CHARS,
+ PLUGIN_TRIGGER_MAX_ITEMS,
+ PLUGIN_TRIGGER_TIMEOUT_MS,
+ composerTriggerKey,
+ type PluginComposerTrigger,
+} from "@pi-desktop/plugin-sdk";
+
+export type PluginTriggerMatch = {
+ readonly trigger: PluginComposerTrigger;
+ readonly query: string;
+ /** Where the symbol sits; accepting replaces `[tokenStart, tokenEnd)`. */
+ readonly tokenStart: number;
+ readonly tokenEnd: number;
+};
+
+/** A row of a trigger's list the host accepted. */
+export type PluginTriggerRow = {
+ readonly label: string;
+ readonly send: string;
+ readonly detail?: string;
+};
+
+const WHITESPACE = /\s/;
+/** Composer chip tokens (private use area) and the snapshot's mark stand-in. */
+const RESERVED_CHARS = /[\uE000-\uF8FF\uFFFC]/;
+const LINE_BREAK = /[\r\n\u2028\u2029]/;
+
+/**
+ * The plugin trigger the caret is in: a word that starts at the beginning of
+ * a line or after whitespace with an owned symbol (full-width forms count)
+ * and runs to the caret. A chip inside the word ends it.
+ */
+export function detectPluginTrigger(
+ value: string,
+ cursor: number,
+ owned: ReadonlySet<PluginComposerTrigger>,
+): PluginTriggerMatch | null {
+ if (owned.size === 0 || cursor <= 0 || cursor > value.length) return null;
+ let start = cursor;
+ while (start > 0 && !WHITESPACE.test(value[start - 1])) start -= 1;
+ if (start === cursor) return null;
+ const trigger = composerTriggerKey(value[start]);
+ if (!trigger || !owned.has(trigger)) return null;
+ const query = value.slice(start + 1, cursor);
+ if (RESERVED_CHARS.test(query)) return null;
+ return { trigger, query, tokenStart: start, tokenEnd: cursor };
+}
+
+function utf8Bytes(text: string): number {
+ return new TextEncoder().encode(text).length;
+}
+
+/**
+ * One item as the host keeps it (`send` defaulted to `label`), or `null` when
+ * it breaks a limit. Marks a plugin writes into the draft pass the same test.
+ */
+export function sanitizeTriggerItem(item: unknown): PluginTriggerRow | null {
+ if (typeof item !== "object" || item === null) return null;
+ const { label, send, detail } = item as Record<string, unknown>;
+ if (typeof label !== "string" || !label.trim()) return null;
+ if (Array.from(label).length > PLUGIN_MARK_LABEL_MAX_CHARS) return null;
+ if (RESERVED_CHARS.test(label) || LINE_BREAK.test(label)) return null;
+ const sent = send === undefined ? label : send;
+ if (typeof sent !== "string" || !sent.trim()) return null;
+ if (RESERVED_CHARS.test(sent) || utf8Bytes(sent) > PLUGIN_MARK_SEND_MAX_BYTES) return null;
+ if (detail === undefined) return { label, send: sent };
+ if (typeof detail !== "string") return null;
+ if (Array.from(detail).length > PLUGIN_TRIGGER_DETAIL_MAX_CHARS) return null;
+ return { label, send: sent, detail };
+}
+
+/**
+ * The rows the host keeps of a trigger's answer: items breaking a limit are
+ * dropped one by one, the rest cut at `PLUGIN_TRIGGER_MAX_ITEMS`. An answer
+ * that is no array is no answer (`null`).
+ */
+export function sanitizeTriggerItems(answer: unknown): PluginTriggerRow[] | null {
+ if (!Array.isArray(answer)) return null;
+ const rows: PluginTriggerRow[] = [];
+ for (const item of answer) {
+ const row = sanitizeTriggerItem(item);
+ if (row) rows.push(row);
+ if (rows.length === PLUGIN_TRIGGER_MAX_ITEMS) break;
+ }
+ return rows;
+}
+
+/**
+ * Ask a trigger for its items. Resolves with the kept rows, or `null` when
+ * the provider throws, rejects, answers with no array or not within
+ * `timeoutMs`; never rejects. A failure is logged, since the group it
+ * collapses is the only trace the user sees.
+ */
+export function askPluginTrigger(
+ provider: (query: { trigger: PluginComposerTrigger; query: string }) => unknown,
+ match: Pick<PluginTriggerMatch, "trigger" | "query">,
+ label: string,
+ timeoutMs = PLUGIN_TRIGGER_TIMEOUT_MS,
+): Promise<PluginTriggerRow[] | null> {
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (rows: PluginTriggerRow[] | null, why?: unknown) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (rows === null) console.warn(`[plugin-slot] ${label} composerTrigger failed`, why);
+ resolve(rows);
+ };
+ const timer = setTimeout(
+ () => finish(null, new Error(`no answer within ${timeoutMs} ms`)),
+ timeoutMs,
+ );
+ try {
+ Promise.resolve(provider({ trigger: match.trigger, query: match.query })).then(
+ (answer) => {
+ try {
+ const rows = sanitizeTriggerItems(answer);
+ finish(rows, rows ? undefined : new Error("the answer is not an array"));
+ } catch (error) {
+ finish(null, error);
+ }
+ },
+ (error: unknown) => finish(null, error),
+ );
+ } catch (error) {
+ finish(null, error);
+ }
+ });
+}
diff --git a/apps/desktop/src/lib/composer-draft-cache.ts b/apps/desktop/src/lib/composer-draft-cache.ts
index fce998c92..f496c17be 100644
--- a/apps/desktop/src/lib/composer-draft-cache.ts
+++ b/apps/desktop/src/lib/composer-draft-cache.ts
@@ -1,4 +1,8 @@
-import type { ComposerDraftSnapshot } from "./composer-smart-stop";
+import type {
+ ComposerDraftFileReference,
+ ComposerDraftSnapshot,
+ ComposerPluginPart,
+} from "./composer-smart-stop";
type CachedComposerDraft = ComposerDraftSnapshot & {
/** Workspace that owned relative file references when the draft was captured. */
@@ -23,8 +27,56 @@ export type ComposerDraftFileInput = {
kind?: "image" | "file";
mimeType?: string;
token?: string;
+ plugin?: ComposerPluginPart;
};
+/** The draft-snapshot form of a live reference: its fields without session or id. */
+export function draftFileReference({
+ path,
+ name,
+ kind,
+ mimeType,
+ token,
+ plugin,
+}: ComposerDraftFileInput): ComposerDraftFileReference {
+ return {
+ path,
+ name,
+ kind,
+ ...(mimeType ? { mimeType } : {}),
+ ...(token ? { token } : {}),
+ ...(plugin ? { plugin } : {}),
+ };
+}
+
+function samePluginPart(a?: ComposerPluginPart, b?: ComposerPluginPart): boolean {
+ if (a === b) return true;
+ if (!a || !b || a.kind !== b.kind || a.pluginId !== b.pluginId) return false;
+ switch (a.kind) {
+ case "mark":
+ return a.send === (b as typeof a).send;
+ case "fold":
+ return a.send === (b as typeof a).send && a.count === (b as typeof a).count;
+ case "attachment":
+ return a.id === (b as typeof a).id && a.size === (b as typeof a).size;
+ }
+}
+
+/** Whether two references are the same draft content, whatever their session or id. */
+export function sameDraftFileReference(
+ a: ComposerDraftFileInput,
+ b: ComposerDraftFileInput,
+): boolean {
+ return (
+ a.path === b.path &&
+ a.name === b.name &&
+ a.kind === b.kind &&
+ a.mimeType === b.mimeType &&
+ a.token === b.token &&
+ samePluginPart(a.plugin, b.plugin)
+ );
+}
+
const cache = new Map<string, CachedComposerDraft>();
const revisions = new Map<string, number>();
let revisionCounter = 0;
@@ -49,13 +101,7 @@ export function snapshotComposerDraft(
text,
fileReferences: fileReferences
.filter((fileReference) => (fileReference.sessionId ?? "") === owner)
- .map(({ path, name, kind, mimeType, token }) => ({
- path,
- name,
- kind,
- ...(mimeType ? { mimeType } : {}),
- ...(token ? { token } : {}),
- })),
+ .map(draftFileReference),
};
if (workspacePath !== undefined) snapshot.workspacePath = workspacePath;
return snapshot;
diff --git a/apps/desktop/src/lib/composer-smart-stop.ts b/apps/desktop/src/lib/composer-smart-stop.ts
index 94b66c0e2..01d525b73 100644
--- a/apps/desktop/src/lib/composer-smart-stop.ts
+++ b/apps/desktop/src/lib/composer-smart-stop.ts
@@ -1,3 +1,27 @@
+/**
+ * What a plugin put in the draft (`docs/plugin-plan/render/draft/`,
+ * `docs/plugin-plan/render/attachments/`):
+ * - `mark`: a chip showing the reference's `name` that sends `send`;
+ * - `fold`: the one chip holding the marks past the per-draft limit, sending
+ * their `send` texts joined by spaces; `pluginId` is the first one's;
+ * - `attachment`: a file the plugin staged, owned by it for `attachments.*`.
+ * Parts are immutable; a change is a new object.
+ */
+export type ComposerPluginPart =
+ | { readonly kind: "mark"; readonly pluginId: string; readonly send: string }
+ | {
+ readonly kind: "fold";
+ readonly pluginId: string;
+ readonly send: string;
+ readonly count: number;
+ }
+ | {
+ readonly kind: "attachment";
+ readonly pluginId: string;
+ readonly id: string;
+ readonly size: number;
+ };
+
export type ComposerDraftFileReference = {
path: string;
name: string;
@@ -5,6 +29,7 @@ export type ComposerDraftFileReference = {
mimeType?: string;
/** Visible inline token for a generated large-text paste reference. */
token?: string;
+ plugin?: ComposerPluginPart;
};
export type ComposerDraftSnapshot = {
diff --git a/apps/desktop/src/plugins/renderer-host/composer-actions.ts b/apps/desktop/src/plugins/renderer-host/composer-actions.ts
new file mode 100644
index 000000000..0e9cc25ed
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-host/composer-actions.ts
@@ -0,0 +1,214 @@
+/**
+ * The composer words of `pi.dispatch` (`docs/plugin-plan/render/draft/`,
+ * `docs/plugin-plan/render/attachments/`): the payload checks that need no
+ * draft, then the draft bridge, which owns everything that does. None of them
+ * leaves the renderer.
+ */
+import {
+ PLUGIN_ATTACHMENT_MAX_BYTES,
+ PLUGIN_DRAFT_MARK_CHAR,
+ PLUGIN_DRAFT_TEXT_MAX_BYTES,
+ PLUGIN_INSERT_TEXT_MAX_BYTES,
+ type PluginRendererActionName,
+ type PluginRendererErrorCode,
+} from "@pi-desktop/plugin-sdk";
+import type {
+ AttachmentInput,
+ ComposerDraftBridge,
+ DraftReplaceInput,
+} from "../../features/chat/composer/plugins/draft-bridge";
+import type { DraftMarkInput } from "../../features/chat/composer/plugins/plugin-draft";
+import { sanitizeTriggerItem } from "../../features/chat/composer/plugins/plugin-triggers";
+import { PluginRendererError } from "../renderer-error";
+
+/** The bridge calls the composer words end in. */
+export type ComposerRoutes = Pick<
+ ComposerDraftBridge,
+ | "insertText"
+ | "readDraft"
+ | "replaceDraft"
+ | "addAttachment"
+ | "listAttachments"
+ | "removeAttachment"
+>;
+
+const utf8 = new TextEncoder();
+
+function refuse(code: PluginRendererErrorCode, message: string): never {
+ throw new PluginRendererError(code, message);
+}
+
+function invalid(message: string): never {
+ refuse("PLUGIN_ACTION_INVALID_PAYLOAD", message);
+}
+
+function onlyKeys(payload: Record<string, unknown>, action: string, keys: readonly string[]): void {
+ const extra = Object.keys(payload).find((key) => !keys.includes(key));
+ if (extra !== undefined) invalid(`${action} takes no ${JSON.stringify(extra)}`);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function insertTextInput(payload: Record<string, unknown>): string {
+ const text = payload.text;
+ if (
+ typeof text !== "string" ||
+ !text ||
+ utf8.encode(text).byteLength > PLUGIN_INSERT_TEXT_MAX_BYTES
+ ) {
+ invalid(
+ `composer.insertText requires non-empty text of at most ${PLUGIN_INSERT_TEXT_MAX_BYTES} UTF-8 bytes`,
+ );
+ }
+ return text;
+}
+
+function markInput(mark: unknown, index: number): DraftMarkInput {
+ const where = `composer.replaceDraft marks[${index}]`;
+ if (!isRecord(mark)) invalid(`${where} must be an object`);
+ if ("id" in mark) {
+ onlyKeys(mark, where, ["id"]);
+ if (typeof mark.id !== "string" || !mark.id) invalid(`${where}.id must be a mark id`);
+ return { id: mark.id };
+ }
+ onlyKeys(mark, where, ["label", "send"]);
+ const row = sanitizeTriggerItem(mark);
+ if (!row) invalid(`${where} breaks the mark limits (label, send)`);
+ return { label: row.label, send: row.send };
+}
+
+function replaceDraftInput(payload: Record<string, unknown>): DraftReplaceInput {
+ const action = "composer.replaceDraft";
+ onlyKeys(payload, action, ["expectedGeneration", "text", "marks"]);
+ const { expectedGeneration, text, marks = [] } = payload;
+ if (!Number.isSafeInteger(expectedGeneration) || (expectedGeneration as number) < 0) {
+ invalid(`${action} requires the expectedGeneration of a snapshot`);
+ }
+ if (typeof text !== "string" || utf8.encode(text).byteLength > PLUGIN_DRAFT_TEXT_MAX_BYTES) {
+ invalid(`${action} requires text of at most ${PLUGIN_DRAFT_TEXT_MAX_BYTES} UTF-8 bytes`);
+ }
+ if (!Array.isArray(marks)) invalid(`${action} marks must be an array`);
+ const slots = text.split(PLUGIN_DRAFT_MARK_CHAR).length - 1;
+ if (slots !== marks.length) {
+ invalid(`${action} text has ${slots} mark chars for ${marks.length} marks`);
+ }
+ return {
+ expectedGeneration: expectedGeneration as number,
+ text,
+ marks: marks.map(markInput),
+ };
+}
+
+// Control characters and path separators have no place in a file name.
+const NAME_FORBIDDEN = /[\u0000-\u001F\u007F/\\]/;
+const NAME_EXTENSION = /[^.]\.[A-Za-z0-9]+$/;
+const MIME_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
+/**
+ * A string that is a single-line path or URL is a reference to content, not
+ * content: S1 has the host refuse it rather than read it.
+ */
+const REFERENCE =
+ /^(?:[a-z][a-z0-9+.-]*:\/\/|(?:file|data|blob|https?|ftp):|[a-z]:[\\/]|\/|~\/|\.\.?\/|\\\\)/i;
+
+function attachmentInput(payload: Record<string, unknown>): AttachmentInput {
+ const action = "attachments.add";
+ if ("token" in payload) {
+ invalid(`${action} takes the content itself; the token form is reserved`);
+ }
+ onlyKeys(payload, action, ["name", "mimeType", "content"]);
+ const { name, mimeType, content } = payload;
+ if (
+ typeof name !== "string" ||
+ name.length > 255 ||
+ NAME_FORBIDDEN.test(name) ||
+ !NAME_EXTENSION.test(name)
+ ) {
+ invalid(`${action} name must be a file name with an extension`);
+ }
+ if (typeof mimeType !== "string" || !MIME_TYPE.test(mimeType)) {
+ invalid(`${action} mimeType must be a type/subtype`);
+ }
+ let bytes: Uint8Array;
+ if (typeof content === "string") {
+ const line = content.trim();
+ if (!/[\r\n]/.test(line) && REFERENCE.test(line)) {
+ refuse(
+ "PLUGIN_ATTACHMENT_REFERENCE_REFUSED",
+ `${action} takes the file's content, not a path or URL to it`,
+ );
+ }
+ bytes = utf8.encode(content);
+ } else if (content instanceof ArrayBuffer) {
+ bytes = new Uint8Array(content);
+ } else if (content instanceof Uint8Array) {
+ bytes = content;
+ } else {
+ invalid(`${action} content must be a string, an ArrayBuffer or a Uint8Array`);
+ }
+ if (bytes.byteLength > PLUGIN_ATTACHMENT_MAX_BYTES) {
+ refuse("PLUGIN_ATTACHMENT_LIMIT", `an attachment holds at most ${PLUGIN_ATTACHMENT_MAX_BYTES} bytes`);
+ }
+ // A copy, so the plugin cannot change the bytes while they are staged.
+ const data = bytes.slice().buffer as ArrayBuffer;
+ return { name, mimeType, data };
+}
+
+/**
+ * Run one composer word for `pluginId`. `userGesture` is whether the
+ * dispatch started inside a user's input event.
+ */
+export function runComposerAction(
+ pluginId: string,
+ action: Exclude<PluginRendererActionName, "plugin.call">,
+ payload: Record<string, unknown>,
+ routes: ComposerRoutes,
+ userGesture: boolean,
+): unknown {
+ switch (action) {
+ case "composer.insertText":
+ return routes.insertText(insertTextInput(payload));
+ case "composer.readDraft":
+ return routes.readDraft(pluginId);
+ case "composer.replaceDraft":
+ return routes.replaceDraft(pluginId, replaceDraftInput(payload), userGesture);
+ case "attachments.add":
+ return routes.addAttachment(pluginId, attachmentInput(payload));
+ case "attachments.list":
+ return routes.listAttachments(pluginId);
+ case "attachments.remove": {
+ const id = payload.id;
+ if (typeof id !== "string" || !id) invalid("attachments.remove requires an attachment id");
+ return routes.removeAttachment(pluginId, id);
+ }
+ }
+}
+
+const GESTURE_EVENTS = new Set([
+ "click",
+ "dblclick",
+ "auxclick",
+ "contextmenu",
+ "keydown",
+ "keyup",
+ "keypress",
+ "pointerdown",
+ "pointerup",
+ "mousedown",
+ "mouseup",
+ "touchstart",
+ "touchend",
+ "input",
+ "change",
+ "submit",
+]);
+
+/**
+ * Whether code runs inside the handler of a user's own input event: one the
+ * browser dispatched (`isTrusted`) of a kind only a person causes. A timer, a
+ * network answer or a `plugin.call` reply runs outside any event.
+ */
+export function isUserGesture(event: Event | undefined = globalThis.window?.event): boolean {
+ return event !== undefined && event.isTrusted && GESTURE_EVENTS.has(event.type);
+}
diff --git a/apps/desktop/src/plugins/renderer-host/dispatch.ts b/apps/desktop/src/plugins/renderer-host/dispatch.ts
index af327faa2..ca36e5103 100644
--- a/apps/desktop/src/plugins/renderer-host/dispatch.ts
+++ b/apps/desktop/src/plugins/renderer-host/dispatch.ts
@@ -6,32 +6,36 @@
* to its `manifest.rendererActions`, so a component can only ever act as its
* own plugin and only through the words it declared. `plugin.call` crosses to
* the plugin's headless entry through the main-process relay, which owns the
- * method whitelist, the size and rate limits and the breaker;
- * `composer.insertText` never leaves the renderer and goes through the
- * composer's insert bridge. Closing the channel when its load ends refuses
+ * method whitelist, the size and rate limits and the breaker; the composer
+ * words never leave the renderer and go through the composer's draft bridge
+ * (`./composer-actions.ts`). Closing the channel when its load ends refuses
* every later dispatch and rejects the calls still in flight, so a late
* answer never reaches the components of an unloaded plugin.
*/
import {
- PLUGIN_INSERT_TEXT_MAX_BYTES,
PLUGIN_RENDERER_ACTIONS,
+ type PluginRendererActionName,
type PluginRendererDispatch,
} from "@pi-desktop/plugin-sdk";
-import { insertComposerText } from "../../features/chat/composer/insert-bridge";
+import { composerDraftBridge } from "../../features/chat/composer/plugins/draft-bridge";
import { api } from "../../lib/api";
import { PluginRendererError } from "../renderer-error";
+import { isUserGesture, runComposerAction, type ComposerRoutes } from "./composer-actions";
/** Where the implemented words go. The defaults are the live app's. */
export type DispatchRoutes = {
/** The main-process `plugin.call` relay; rejects with its coded errors. */
pluginCall(pluginId: string, method: string, args: unknown): Promise<unknown>;
- /** Inserts at the composer caret; false when no composer is mounted. */
- insertText(text: string): boolean;
+ /** The composer words: the draft bridge of the composer taking input. */
+ composer: ComposerRoutes;
+ /** Whether the code runs inside a user's input event now. */
+ userGesture(): boolean;
};
const appRoutes: DispatchRoutes = {
pluginCall: (pluginId, method, args) => api.pluginRendererCall(pluginId, method, args),
- insertText: insertComposerText,
+ composer: composerDraftBridge,
+ userGesture: () => isUserGesture(),
};
export type DispatchChannel = {
@@ -41,8 +45,6 @@ export type DispatchChannel = {
close(): void;
};
-const utf8 = new TextEncoder();
-
function describe(value: unknown): string {
return typeof value === "string" ? JSON.stringify(value) : typeof value;
}
@@ -92,6 +94,8 @@ export function createDispatchChannel(
});
const dispatch = async (action: unknown, payload: unknown): Promise<unknown> => {
+ // First, while the caller's event is still the current one.
+ const userGesture = routes.userGesture();
if (closed) throw unloaded();
if (
typeof action !== "string" ||
@@ -121,24 +125,19 @@ export function createDispatchChannel(
}
return untilClosed(routes.pluginCall(pluginId, method, jsonArgs(payload.args)));
}
- const text = payload.text;
- if (
- typeof text !== "string" ||
- !text ||
- utf8.encode(text).byteLength > PLUGIN_INSERT_TEXT_MAX_BYTES
- ) {
- throw new PluginRendererError(
- "PLUGIN_ACTION_INVALID_PAYLOAD",
- `composer.insertText requires non-empty text of at most ${PLUGIN_INSERT_TEXT_MAX_BYTES} UTF-8 bytes`,
- );
- }
- if (!routes.insertText(text)) {
- throw new PluginRendererError(
- "PLUGIN_ACTION_NO_COMPOSER",
- "no composer is mounted to take the text",
- );
- }
- return { ok: true };
+ return untilClosed(
+ new Promise((resolve) => {
+ resolve(
+ runComposerAction(
+ pluginId,
+ action as Exclude<PluginRendererActionName, "plugin.call">,
+ payload,
+ routes.composer,
+ userGesture,
+ ),
+ );
+ }),
+ );
};
return {
diff --git a/apps/desktop/src/plugins/renderer-host/loader.ts b/apps/desktop/src/plugins/renderer-host/loader.ts
index 674d49f1d..8630470f9 100644
--- a/apps/desktop/src/plugins/renderer-host/loader.ts
+++ b/apps/desktop/src/plugins/renderer-host/loader.ts
@@ -8,8 +8,8 @@
* evaluates the new code instead of its cached module graph, and the old URLs
* stop resolving.
*
- * Each load is its own session. Registrations, style sheets, layers and the
- * dispatch channel belong to the load that made them, and ending the load
+ * Each load is its own session. Registrations, style sheets, layers, draft
+ * subscriptions and the dispatch channel belong to the load that made them, and ending the load
* disposes all of them before the plugin's `onUnload` runs, whatever the
* plugin does or fails to do. The `pi` of an ended load stays dead:
* registering, injecting or opening a layer through it throws
@@ -22,6 +22,7 @@ import {
type PiRendererApi,
type PiRendererModule,
type PluginDisposer,
+ type PluginDraftListener,
type PluginLayer,
type PluginSlotRegistration,
} from "@pi-desktop/plugin-sdk";
@@ -30,6 +31,7 @@ import {
type PluginRendererDescriptor,
type PluginSummary,
} from "@pi-desktop/shared";
+import { composerDraftBridge } from "../../features/chat/composer/plugins/draft-bridge";
import { PluginRendererError } from "../renderer-error";
import { pluginLayers } from "../renderer-layers/layer-stack";
import { slotRegistry, type SlotRegistry } from "../renderer-slots/registry";
@@ -54,6 +56,7 @@ export type RendererLoaderDeps = {
injectStyle(pluginId: string, css: string): PluginDisposer;
openLayer(pluginId: string): PluginLayer;
openChannel(pluginId: string, actions: readonly string[]): DispatchChannel;
+ subscribeDraft(pluginId: string, listener: PluginDraftListener): PluginDisposer;
warn(message: string, error: unknown): void;
};
@@ -135,6 +138,22 @@ class RendererLoad {
return Object.freeze({ element: layer.element, close: this.track(layer.close) });
},
}),
+ composer: Object.freeze({
+ subscribeDraft: (listener: PluginDraftListener) => {
+ this.assertAlive();
+ // Following the draft reads it, so it takes the same declaration.
+ if (!descriptor.actions.includes("composer.readDraft")) {
+ throw new PluginRendererError(
+ "PLUGIN_ACTION_UNDECLARED",
+ `composer.readDraft is not in ${pluginId}'s manifest.rendererActions`,
+ );
+ }
+ if (typeof listener !== "function") {
+ throw new TypeError("composer.subscribeDraft takes a listener function");
+ }
+ return this.track(this.deps.subscribeDraft(pluginId, listener));
+ },
+ }),
dispatch: this.channel.dispatch,
});
}
@@ -277,5 +296,6 @@ export const rendererModules = new RendererModuleLoader({
injectStyle: injectPluginStyle,
openLayer: (pluginId) => pluginLayers.open(pluginId),
openChannel: (pluginId, actions) => createDispatchChannel(pluginId, actions),
+ subscribeDraft: (pluginId, listener) => composerDraftBridge.subscribe(pluginId, listener),
warn: (message, error) => console.warn(message, error),
});
diff --git a/apps/desktop/src/plugins/renderer-slots/registry.ts b/apps/desktop/src/plugins/renderer-slots/registry.ts
index 74954b1d8..69c916855 100644
--- a/apps/desktop/src/plugins/renderer-slots/registry.ts
+++ b/apps/desktop/src/plugins/renderer-slots/registry.ts
@@ -7,18 +7,23 @@
*
* Additive slots stack in registration order and never clash. Keyed slots
* (`toolCard` by the plugin's qualified tool name, `blockRenderer` by its
- * language tag) refuse a second claim of a key with `PLUGIN_SLOT_DUPLICATE`:
- * the first registration keeps it. Every registration comes back as a
+ * language tag, `composerTrigger` by its symbol) refuse a second claim of a
+ * key with `PLUGIN_SLOT_DUPLICATE`: the first registration keeps it.
+ * `composerTrigger` registers no component, so its entries are kept apart
+ * from the component entries outlets render. Every registration comes back as a
* disposer; the loader holds the disposers of one load and runs them all when
* the plugin unloads.
*/
import {
PLUGIN_SLOT_POSITIONS,
blockRendererLanguageKey,
+ composerTriggerKey,
pluginToolName,
slotRegistrationRefusal,
+ type PluginComponentSlot,
+ type PluginComposerTrigger,
+ type PluginComposerTriggerRegistration,
type PluginDisposer,
- type PluginRendererSlot,
type PluginSlotPosition,
type PluginSlotRegistration,
} from "@pi-desktop/plugin-sdk";
@@ -27,7 +32,7 @@ import { PluginRendererError } from "../renderer-error";
export type SlotEntry = {
readonly id: string;
readonly pluginId: string;
- readonly slot: PluginRendererSlot;
+ readonly slot: PluginComponentSlot;
/**
* The plugin's function component. Its type admits no call: outlets render
* it through `slotElement`, as an element that owns its hooks.
@@ -45,14 +50,26 @@ export type SlotEntry = {
readonly toolName?: string;
};
+/** A `composerTrigger` registration: the symbol it owns and its provider. */
+export type TriggerEntry = {
+ readonly id: string;
+ readonly pluginId: string;
+ readonly trigger: PluginComposerTrigger;
+ readonly items: PluginComposerTriggerRegistration["items"];
+};
+
export type SlotRegistrySnapshot = {
/** Bumped on every mutation; the `useSyncExternalStore` change signal. */
readonly version: number;
/** Registration order across plugins is the presentation order. */
readonly entries: readonly SlotEntry[];
+ /** At most one per symbol. */
+ readonly triggers: readonly TriggerEntry[];
};
-function sidesOf(registration: PluginSlotRegistration): readonly PluginSlotPosition[] {
+type ComponentRegistration = Exclude<PluginSlotRegistration, PluginComposerTriggerRegistration>;
+
+function sidesOf(registration: ComponentRegistration): readonly PluginSlotPosition[] {
switch (registration.slot) {
case "userAction":
case "assistantAction":
@@ -68,7 +85,7 @@ function sidesOf(registration: PluginSlotRegistration): readonly PluginSlotPosit
function keyOf(
pluginId: string,
- registration: PluginSlotRegistration,
+ registration: ComponentRegistration,
): Pick<SlotEntry, "key" | "toolName"> {
if (registration.slot === "toolCard") {
return {
@@ -83,7 +100,7 @@ function keyOf(
}
export class SlotRegistry {
- private state: SlotRegistrySnapshot = { version: 0, entries: [] };
+ private state: SlotRegistrySnapshot = { version: 0, entries: [], triggers: [] };
private readonly listeners = new Set<() => void>();
private lastId = 0;
@@ -96,11 +113,28 @@ export class SlotRegistry {
getSnapshot = (): SlotRegistrySnapshot => this.state;
- private commit(entries: readonly SlotEntry[]): void {
- this.state = { version: this.state.version + 1, entries };
+ private commit(next: Partial<Omit<SlotRegistrySnapshot, "version">>): void {
+ this.state = { ...this.state, ...next, version: this.state.version + 1 };
for (const listener of this.listeners) listener();
}
+ private duplicate(slot: string, key: string, holder: { pluginId: string }): PluginRendererError {
+ return new PluginRendererError(
+ "PLUGIN_SLOT_DUPLICATE",
+ `${slot} ${JSON.stringify(key)} is already registered by ${holder.pluginId}`,
+ );
+ }
+
+ /** A disposer that runs `remove` once. */
+ private disposer(remove: () => void): PluginDisposer {
+ let disposed = false;
+ return () => {
+ if (disposed) return;
+ disposed = true;
+ remove();
+ };
+ }
+
/**
* Accept one registration of `pluginId` or throw a `PluginRendererError`
* with a `PluginSlotErrorCode`. `ownTools` is the plugin's bare
@@ -111,17 +145,13 @@ export class SlotRegistry {
const refusal = slotRegistrationRefusal(pluginId, registration, ownTools);
if (refusal) throw new PluginRendererError(refusal.code, refusal.message);
const accepted = registration as PluginSlotRegistration;
+ if (accepted.slot === "composerTrigger") return this.registerTrigger(pluginId, accepted);
const keyed = keyOf(pluginId, accepted);
if (keyed.key !== undefined) {
const holder = this.state.entries.find(
(entry) => entry.slot === accepted.slot && entry.key === keyed.key,
);
- if (holder) {
- throw new PluginRendererError(
- "PLUGIN_SLOT_DUPLICATE",
- `${accepted.slot} ${JSON.stringify(keyed.key)} is already registered by ${holder.pluginId}`,
- );
- }
+ if (holder) throw this.duplicate(accepted.slot, keyed.key, holder);
}
const entry: SlotEntry = {
id: `slot-${++this.lastId}`,
@@ -131,31 +161,53 @@ export class SlotRegistry {
sides: sidesOf(accepted),
...keyed,
};
- this.commit([...this.state.entries, entry]);
- let disposed = false;
- return () => {
- if (disposed) return;
- disposed = true;
- this.commit(this.state.entries.filter((candidate) => candidate !== entry));
+ this.commit({ entries: [...this.state.entries, entry] });
+ return this.disposer(() =>
+ this.commit({ entries: this.state.entries.filter((candidate) => candidate !== entry) }),
+ );
+ }
+
+ private registerTrigger(
+ pluginId: string,
+ registration: PluginComposerTriggerRegistration,
+ ): PluginDisposer {
+ // The refusal check has already accepted the symbol.
+ const trigger = composerTriggerKey(registration.trigger) as PluginComposerTrigger;
+ const holder = this.triggerFor(trigger);
+ if (holder) throw this.duplicate(registration.slot, trigger, holder);
+ const entry: TriggerEntry = {
+ id: `slot-${++this.lastId}`,
+ pluginId,
+ trigger,
+ items: registration.items,
};
+ this.commit({ triggers: [...this.state.triggers, entry] });
+ return this.disposer(() =>
+ this.commit({ triggers: this.state.triggers.filter((candidate) => candidate !== entry) }),
+ );
}
/** Every registration of a slot, in registration order. */
- entriesFor(slot: PluginRendererSlot): SlotEntry[] {
+ entriesFor(slot: PluginComponentSlot): SlotEntry[] {
return this.state.entries.filter((entry) => entry.slot === slot);
}
/** A positioned slot's registrations on one side, in registration order. */
- entriesForSide(slot: PluginRendererSlot, side: PluginSlotPosition): SlotEntry[] {
+ entriesForSide(slot: PluginComponentSlot, side: PluginSlotPosition): SlotEntry[] {
return this.state.entries.filter(
(entry) => entry.slot === slot && entry.sides.includes(side),
);
}
/** The one registration holding a key: a tool's card, a language's renderer. */
- entryForKey(slot: PluginRendererSlot, key: string): SlotEntry | undefined {
+ entryForKey(slot: PluginComponentSlot, key: string): SlotEntry | undefined {
return this.state.entries.find((entry) => entry.slot === slot && entry.key === key);
}
+
+ /** The plugin owning a composer symbol, if any. */
+ triggerFor(trigger: PluginComposerTrigger): TriggerEntry | undefined {
+ return this.state.triggers.find((entry) => entry.trigger === trigger);
+ }
}
/** The app-wide registry the loader registers into and outlets read from. */
diff --git a/apps/desktop/src/plugins/renderer-slots/slot-shell.css b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
index 6e7c468b2..972fb10cc 100644
--- a/apps/desktop/src/plugins/renderer-slots/slot-shell.css
+++ b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
@@ -15,6 +15,16 @@
min-width: 0;
}
+/*
+ * A toolbar control shrinks with the row, and what no longer fits is cut at
+ * its own edge instead of painting over the next control. Only across: a
+ * popover a control opens above the toolbar still shows.
+ */
+.pi-plugin-slot[data-pi-slot="composerControl"] {
+ overflow-x: clip;
+ overflow-clip-margin: 2px;
+}
+
/* Slots that own a whole block of the transcript take its full width. */
.pi-plugin-slot[data-pi-slot="entryExtra"],
.pi-plugin-slot[data-pi-slot="toolCard"],
diff --git a/apps/desktop/src/plugins/renderer-slots/use-slots.tsx b/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
index a5f42208c..a547303f1 100644
--- a/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
+++ b/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
@@ -14,7 +14,7 @@ import {
useMemo,
useSyncExternalStore,
} from "react";
-import type { PluginRendererSlot, PluginSlotPosition } from "@pi-desktop/plugin-sdk";
+import type { PluginComponentSlot, PluginSlotPosition } from "@pi-desktop/plugin-sdk";
import { slotRegistry, type SlotEntry } from "./registry";
/**
@@ -26,7 +26,7 @@ export function slotElement<Props extends object>(entry: SlotEntry, props: Props
}
export function useSlotEntries(
- slot: PluginRendererSlot,
+ slot: PluginComponentSlot,
side?: PluginSlotPosition,
): SlotEntry[] {
const snapshot = useSyncExternalStore(
@@ -42,7 +42,7 @@ export function useSlotEntries(
}
export function useSlotEntryForKey(
- slot: PluginRendererSlot,
+ slot: PluginComponentSlot,
key: string | undefined,
): SlotEntry | undefined {
const snapshot = useSyncExternalStore(
diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.css
index 97ef5ff6e..f43d631cb 100644
--- a/apps/desktop/src/styles/composer.css
+++ b/apps/desktop/src/styles/composer.css
@@ -313,6 +313,12 @@
outline-offset: 1px;
}
+/* A plugin mark: text the plugin sends in its place, not a file. */
+.composer-chip[data-plugin-mark] {
+ background: color-mix(in oklab, var(--ds-accent) 14%, var(--ds-tile-deep));
+ color: var(--ds-text-primary);
+}
+
.composer-chip-icon {
display: inline-flex;
flex: 0 0 auto;
diff --git a/apps/desktop/test/composer-file-reference-display.test.mjs b/apps/desktop/test/composer-file-reference-display.test.mjs
index ecc3be096..81cdd99f1 100644
--- a/apps/desktop/test/composer-file-reference-display.test.mjs
+++ b/apps/desktop/test/composer-file-reference-display.test.mjs
@@ -52,12 +52,14 @@ test("accepted files become compact references while directories keep completion
);
assert.match(composer, /applyEditorDraft\(\s*nextText,/);
// Workspace switches still drop relative `@` chips, not every token-backed
- // chip — paste/scratch paths are absolute and must survive.
+ // chip — paste/scratch paths are absolute and plugin marks carry no path,
+ // so both must survive.
assert.match(composer, /function isPersistedScratchReference\(path: string\)/);
assert.match(
composer,
- /kept = current\.filter\(\(fileReference\) =>\s*isPersistedScratchReference\(fileReference\.path\)/,
+ /Boolean\(fileReference\.plugin\) \|\| isPersistedScratchReference\(fileReference\.path\)/,
);
+ assert.match(composer, /kept = current\.filter\(survives\)/);
assert.doesNotMatch(
composer,
/current\.filter\(\(fileReference\) => Boolean\(fileReference\.token\)\)/,
@@ -72,7 +74,9 @@ test("composer renders atomic inline chips and serializes paths on send", () =>
assert.match(composer, /chip\.dataset\.token = token/);
assert.match(composer, /composer-chip-name/);
assert.match(composer, /nameSpan\.textContent = reference\.name/);
- assert.match(composer, /chip\.title = reference\.path/);
+ // A file chip's title is its path; a plugin mark's is its plugin.
+ assert.match(composer, /isPluginMark\(reference\) \? \(reference\.plugin\?\.pluginId \?\? ""\) : reference\.path/);
+ assert.match(composer, /chip\.title = origin/);
assert.match(
composer,
/serializeComposerFileReferences\(text, activeFileReferences\)/,
diff --git a/apps/desktop/test/composer-plugin-draft.test.mjs b/apps/desktop/test/composer-plugin-draft.test.mjs
new file mode 100644
index 000000000..d16b45452
--- /dev/null
+++ b/apps/desktop/test/composer-plugin-draft.test.mjs
@@ -0,0 +1,426 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * The composer draft as plugins read and write it
+ * (`docs/plugin-plan/render/draft/`, `docs/plugin-plan/render/attachments/`):
+ * the per-plugin view, the replacement plan, and the bridge that owns the
+ * generation, the gates and the attachments of the composer taking input.
+ */
+const { PLUGIN_ATTACHMENTS_MAX, PLUGIN_DRAFT_MAX_MARKS } = await import("@pi-desktop/plugin-sdk");
+const { createFileReference, nextChipToken } = await import(
+ "../src/features/chat/composer/editor.ts"
+);
+const { createPluginMark, foldLabel } = await import(
+ "../src/features/chat/composer/plugins/plugin-marks.ts"
+);
+const { draftSignature, planDraftReplacement, pluginDraftView } = await import(
+ "../src/features/chat/composer/plugins/plugin-draft.ts"
+);
+const { ComposerDraftBridge } = await import(
+ "../src/features/chat/composer/plugins/draft-bridge.ts"
+);
+const { PluginRendererError } = await import("../src/plugins/renderer-error.ts");
+
+const SELF = "demo.lab";
+const OTHER = "demo.other";
+const MARK = "\uFFFC";
+const SID = "s1";
+
+function hostChip(name, sessionId = SID) {
+ return createFileReference(`/scratch/${name}`, name, sessionId, {
+ kind: "file",
+ token: nextChipToken(),
+ });
+}
+
+function mark(pluginId, label, send = label) {
+ return createPluginMark({ pluginId, label, send }, SID);
+}
+
+function fold(count) {
+ return createFileReference("", foldLabel(count), SID, {
+ kind: "file",
+ token: nextChipToken(),
+ plugin: { kind: "fold", pluginId: OTHER, send: "folded", count },
+ });
+}
+
+function image(name) {
+ return createFileReference(`/scratch/${name}`, name, SID, { kind: "image", mimeType: "image/png" });
+}
+
+function draftOf(text, references, sessionId = SID) {
+ return { draftKey: sessionId ? `session:${sessionId}` : "home", sessionId, text, references };
+}
+
+function refused(code) {
+ return (error) => {
+ assert.ok(error instanceof PluginRendererError, `expected a PluginRendererError, got ${error}`);
+ assert.equal(error.code, code);
+ return true;
+ };
+}
+
+test("a plugin sees every chip as one mark char, in order, and only its own send text", () => {
+ const file = hostChip("a.ts");
+ const own = mark(SELF, "Issue 7", "issue #7 body");
+ const theirs = mark(OTHER, "PR 3", "pr #3 body");
+ const folded = fold(2);
+ const elsewhere = hostChip("b.ts", "s2");
+ const unused = hostChip("gone.ts");
+ const draft = draftOf(
+ `fix ${own.token} in ${file.token}, see ${theirs.token}${folded.token} ${MARK}`,
+ [file, own, theirs, folded, elsewhere, unused, image("shot.png")],
+ );
+ const view = pluginDraftView(draft, SELF);
+ assert.equal(view.text, `fix ${MARK} in ${MARK}, see ${MARK}${MARK} \uFFFD`);
+ assert.deepEqual(view.marks, [
+ { id: own.id, kind: "plugin", label: "Issue 7", pluginId: SELF, send: "issue #7 body" },
+ { id: file.id, kind: "host", label: "a.ts" },
+ { id: theirs.id, kind: "plugin", label: "PR 3", pluginId: OTHER },
+ { id: folded.id, kind: "fold", label: foldLabel(2), count: 2 },
+ ]);
+ assert.equal(pluginDraftView(draft, OTHER).marks[2].send, "pr #3 body");
+ assert.equal(pluginDraftView(draft, OTHER).marks[0].send, undefined);
+});
+
+test("the signature follows the draft, its key and its own references only", () => {
+ const file = hostChip("a.ts");
+ const base = draftOf(`x${file.token}`, [file]);
+ const signature = draftSignature(base);
+ assert.equal(draftSignature(null), "");
+ assert.equal(draftSignature({ ...base, references: [...base.references, hostChip("b", "s2")] }), signature);
+ assert.notEqual(draftSignature({ ...base, text: `y${file.token}` }), signature);
+ assert.notEqual(draftSignature({ ...base, draftKey: "session:s9" }), signature);
+ assert.notEqual(draftSignature({ ...base, references: [{ ...file, name: "renamed" }] }), signature);
+ assert.notEqual(draftSignature({ ...base, references: [file, image("p.png")] }), signature);
+ const folded = fold(1);
+ const withFold = draftOf(`x${folded.token}`, [folded]);
+ const joined = { ...folded, plugin: { ...folded.plugin, count: 2 } };
+ assert.notEqual(draftSignature({ ...withFold, references: [joined] }), draftSignature(withFold));
+});
+
+test("a replacement moves chips by id, adds the caller's marks and keeps the rest", () => {
+ const file = hostChip("a.ts");
+ const own = mark(SELF, "Old");
+ const theirs = mark(OTHER, "Theirs");
+ const elsewhere = hostChip("b.ts", "s2");
+ const shot = image("shot.png");
+ const draft = draftOf(`${own.token} ${file.token} ${theirs.token}`, [elsewhere, file, own, theirs, shot]);
+
+ const plan = planDraftReplacement(draft, SELF, `${MARK} first, then ${MARK}`, [
+ { id: file.id },
+ { label: "New", send: "new body" },
+ ]);
+ assert.ok(!("code" in plan), JSON.stringify(plan));
+ const created = plan.references.at(-1);
+ assert.equal(plan.text, `${file.token} first, then ${created.token}`);
+ assert.deepEqual(created.plugin, { kind: "mark", pluginId: SELF, send: "new body" });
+ assert.equal(created.name, "New");
+ assert.equal(created.sessionId, SID);
+ assert.deepEqual(
+ plan.references.map((reference) => reference.id),
+ [elsewhere.id, shot.id, file.id, created.id],
+ "other sessions' references and detached images stay; dropped marks go",
+ );
+});
+
+test("a replacement is refused for a dropped anchor, a bad id, a chip token or too many marks", () => {
+ const file = hostChip("a.ts");
+ const folded = fold(3);
+ const own = mark(SELF, "Own");
+ const draft = draftOf(`${file.token}${folded.token}${own.token}`, [file, folded, own]);
+ const anchor = (text, marks) => planDraftReplacement(draft, SELF, text, marks).code;
+
+ assert.equal(anchor(`${MARK}`, [{ id: folded.id }]), "PLUGIN_DRAFT_ANCHOR", "the host chip");
+ assert.equal(anchor(`${MARK}`, [{ id: file.id }]), "PLUGIN_DRAFT_ANCHOR", "the fold");
+ assert.equal(anchor(`${MARK}${MARK}`, [{ id: folded.id }, { id: file.id }]), undefined);
+ assert.equal(
+ anchor(`${MARK}${MARK}${MARK}`, [{ id: file.id }, { id: folded.id }, { id: "composer-file-0" }]),
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ );
+ assert.equal(
+ anchor(`${MARK}${MARK}${MARK}`, [{ id: file.id }, { id: folded.id }, { id: file.id }]),
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ "an id used twice",
+ );
+ assert.equal(
+ anchor(`${MARK}${MARK}${file.token}`, [{ id: file.id }, { id: folded.id }]),
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ "a chip token in the text",
+ );
+ const many = Array.from({ length: PLUGIN_DRAFT_MAX_MARKS }, (_, i) => ({ label: `m${i}`, send: `m${i}` }));
+ assert.equal(
+ anchor(MARK.repeat(PLUGIN_DRAFT_MAX_MARKS + 2), [{ id: file.id }, { id: folded.id }, ...many]),
+ undefined,
+ "the fold is no plugin mark",
+ );
+ assert.equal(
+ anchor(MARK.repeat(PLUGIN_DRAFT_MAX_MARKS + 3), [
+ { id: file.id },
+ { id: folded.id },
+ { id: own.id },
+ ...many,
+ ]),
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ );
+});
+
+/** A composer handle over plain state, the way the composer lends its own. */
+function fakeComposer({ text = "", references = [], sessionId = SID } = {}) {
+ const state = {
+ text,
+ references,
+ sessionId,
+ blocked: false,
+ focused: false,
+ selection: null,
+ writes: [],
+ staged: [],
+ stage: async (sid, file) => ({
+ path: `/scratch/${sid}/${file.name}`,
+ name: file.name,
+ kind: file.mimeType.startsWith("image/") ? "image" : "file",
+ mimeType: file.mimeType,
+ size: file.data.byteLength,
+ }),
+ };
+ const handle = {
+ read: () =>
+ state.blocked
+ ? null
+ : draftOf(state.text, state.references, state.sessionId),
+ focused: () => state.focused,
+ selection: () => state.selection ?? { start: state.text.length, end: state.text.length },
+ write: (next, nextReferences, caret, focus) => state.writes.push({ next, nextReferences, caret, focus }),
+ stage: (sid, file) => {
+ state.staged.push([sid, file]);
+ return state.stage(sid, file);
+ },
+ };
+ /** Render the last write, as the composer does, and publish it. */
+ const render = (bridge) => {
+ const last = state.writes.at(-1);
+ if (last) {
+ state.text = last.next;
+ state.references = last.nextReferences;
+ }
+ bridge.publish(handle);
+ };
+ return { state, handle, render };
+}
+
+function quietBridge() {
+ const warnings = [];
+ return { bridge: new ComposerDraftBridge((...args) => warnings.push(args)), warnings };
+}
+
+test("the generation moves with every change of the live draft, switches included", () => {
+ const { bridge } = quietBridge();
+ assert.throws(() => bridge.readDraft(SELF), refused("PLUGIN_ACTION_NO_COMPOSER"));
+ const composer = fakeComposer({ text: "hello" });
+ const unregister = bridge.register(composer.handle);
+ const first = bridge.readDraft(SELF);
+ assert.equal(first.text, "hello");
+ bridge.publish(composer.handle);
+ assert.equal(bridge.readDraft(SELF).generation, first.generation, "no change, same generation");
+
+ composer.state.text = "hello!";
+ assert.equal(bridge.readDraft(SELF).generation, first.generation + 1, "a read sees the change");
+ composer.state.sessionId = "s2";
+ bridge.publish(composer.handle);
+ assert.equal(bridge.readDraft(SELF).generation, first.generation + 2, "another session's draft");
+
+ // A composer mounted over it takes over until it goes.
+ const over = fakeComposer({ text: "over" });
+ const unregisterOver = bridge.register(over.handle);
+ assert.equal(bridge.readDraft(SELF).text, "over");
+ unregisterOver();
+ unregisterOver();
+ assert.equal(bridge.readDraft(SELF).text, "hello!");
+
+ composer.state.blocked = true;
+ assert.throws(() => bridge.readDraft(SELF), refused("PLUGIN_ACTION_NO_COMPOSER"));
+ composer.state.blocked = false;
+ unregister();
+ assert.throws(() => bridge.insertText("x"), refused("PLUGIN_ACTION_NO_COMPOSER"));
+});
+
+test("insertText replaces the selection and focuses; the bridge reads its write until the render", () => {
+ const { bridge } = quietBridge();
+ const file = hostChip("a.ts");
+ const composer = fakeComposer({ text: `ab${file.token}cd`, references: [file] });
+ bridge.register(composer.handle);
+ const before = bridge.readDraft(SELF).generation;
+ composer.state.selection = { start: 1, end: 2 };
+
+ const result = bridge.insertText("XY");
+ assert.deepEqual(result, { ok: true, generation: before + 1 });
+ assert.deepEqual(
+ composer.state.writes.map(({ next, caret, focus }) => ({ next, caret, focus })),
+ [{ next: `aXY${file.token}cd`, caret: 3, focus: true }],
+ );
+ assert.deepEqual(composer.state.writes[0].nextReferences, [file]);
+ // Before the render the handle still holds the old text.
+ assert.equal(bridge.readDraft(SELF).text, `aXY${MARK}cd`);
+ bridge.insertText("Z");
+ assert.equal(composer.state.writes[1].next, `aXYZ${file.token}cd`, "at the caret of the last write");
+
+ composer.render(bridge);
+ assert.equal(bridge.readDraft(SELF).generation, before + 2, "the render of the write is no change");
+ assert.throws(() => bridge.insertText(`x${file.token}`), refused("PLUGIN_ACTION_INVALID_PAYLOAD"));
+});
+
+test("replaceDraft checks composer, gesture, focus, generation and anchors, in that order", () => {
+ const { bridge } = quietBridge();
+ assert.throws(
+ () => bridge.replaceDraft(SELF, { expectedGeneration: 0, text: "", marks: [] }, false),
+ refused("PLUGIN_ACTION_NO_COMPOSER"),
+ );
+ const file = hostChip("a.ts");
+ const composer = fakeComposer({ text: `see ${file.token}`, references: [file] });
+ bridge.register(composer.handle);
+ const { generation } = bridge.readDraft(SELF);
+ composer.state.focused = true;
+ const dropping = { expectedGeneration: generation - 1, text: "all new", marks: [] };
+
+ assert.throws(() => bridge.replaceDraft(SELF, dropping, false), refused("PLUGIN_DRAFT_REMOTE"));
+ assert.throws(() => bridge.replaceDraft(SELF, dropping, true), refused("PLUGIN_DRAFT_FOCUSED"));
+ composer.state.focused = false;
+ assert.throws(() => bridge.replaceDraft(SELF, dropping, true), refused("PLUGIN_DRAFT_STALE"));
+ const current = { ...dropping, expectedGeneration: generation };
+ assert.throws(() => bridge.replaceDraft(SELF, current, true), refused("PLUGIN_DRAFT_ANCHOR"));
+ assert.deepEqual(composer.state.writes, [], "a refusal writes nothing");
+
+ const result = bridge.replaceDraft(
+ SELF,
+ { expectedGeneration: generation, text: `${MARK} and ${MARK}`, marks: [{ id: file.id }, { label: "N", send: "n" }] },
+ true,
+ );
+ assert.equal(result.generation, generation + 1);
+ const [write] = composer.state.writes;
+ assert.equal(write.focus, false, "a replacement leaves focus alone");
+ assert.equal(write.caret, write.next.length);
+ assert.ok(write.next.startsWith(`${file.token} and `));
+ assert.deepEqual(bridge.readDraft(SELF).marks.map((m) => m.kind), ["host", "plugin"]);
+ assert.throws(
+ () => bridge.replaceDraft(SELF, { ...current, text: `${MARK}`, marks: [{ id: file.id }] }, true),
+ refused("PLUGIN_DRAFT_STALE"),
+ "the old generation is spent",
+ );
+});
+
+test("a subscriber gets the draft now and after each change, null when no composer takes input", () => {
+ const { bridge, warnings } = quietBridge();
+ const seen = [];
+ const stop = bridge.subscribe(SELF, (snapshot) => seen.push(snapshot?.text ?? null));
+ bridge.subscribe(OTHER, () => {
+ throw new Error("listener bug");
+ });
+ assert.deepEqual(seen, [null]);
+ const composer = fakeComposer({ text: "a" });
+ const unregister = bridge.register(composer.handle);
+ bridge.insertText("b");
+ composer.render(bridge);
+ bridge.publish(composer.handle);
+ composer.state.blocked = true;
+ bridge.publish(composer.handle);
+ composer.state.blocked = false;
+ bridge.publish(composer.handle);
+ unregister();
+ stop();
+ stop();
+ const again = fakeComposer({ text: "later" });
+ bridge.register(again.handle);
+ assert.deepEqual(seen, [null, "a", "ab", null, "ab", null]);
+ assert.ok(warnings.length >= 5, "a throwing listener is logged and stays subscribed");
+ assert.match(String(warnings[0][0]), /demo\.other draft listener failed/);
+});
+
+test("attachments are staged into the session's draft, listed and removed per plugin", async () => {
+ const { bridge } = quietBridge();
+ const composer = fakeComposer({ text: "hi" });
+ bridge.register(composer.handle);
+ const bytes = new Uint8Array([1, 2, 3]).buffer;
+
+ const doc = await bridge.addAttachment(SELF, { name: "a.txt", mimeType: "text/plain", data: bytes });
+ assert.equal(typeof doc.id, "string");
+ assert.deepEqual(composer.state.staged, [[SID, { name: "a.txt", mimeType: "text/plain", data: bytes }]]);
+ let write = composer.state.writes.at(-1);
+ const docReference = write.nextReferences.at(-1);
+ assert.equal(write.focus, false);
+ assert.equal(write.next, `hi${docReference.token}`, "a file is a chip at the end");
+ assert.deepEqual(docReference.plugin, { kind: "attachment", pluginId: SELF, id: doc.id, size: 3 });
+ composer.render(bridge);
+
+ const shot = await bridge.addAttachment(SELF, { name: "c.png", mimeType: "image/png", data: bytes });
+ write = composer.state.writes.at(-1);
+ assert.equal(write.next, `hi${docReference.token}`, "an image goes with the draft's images");
+ assert.equal(write.nextReferences.at(-1).token, undefined);
+ composer.render(bridge);
+ const theirs = await bridge.addAttachment(OTHER, { name: "t.txt", mimeType: "text/plain", data: bytes });
+ composer.render(bridge);
+
+ assert.deepEqual(bridge.listAttachments(SELF), [
+ { id: doc.id, name: "a.txt", mimeType: "text/plain", size: 3 },
+ { id: shot.id, name: "c.png", mimeType: "image/png", size: 3 },
+ ]);
+ assert.equal(bridge.readDraft(SELF).marks.filter((m) => m.kind === "host").length, 2, "chips are host marks");
+ assert.throws(() => bridge.removeAttachment(SELF, theirs.id), refused("PLUGIN_ATTACHMENT_NOT_FOUND"));
+ assert.throws(() => bridge.removeAttachment(SELF, "nope"), refused("PLUGIN_ATTACHMENT_NOT_FOUND"));
+ assert.deepEqual(bridge.removeAttachment(SELF, doc.id), { ok: true });
+ write = composer.state.writes.at(-1);
+ assert.equal(write.focus, false);
+ assert.ok(!write.next.includes(docReference.token));
+ composer.render(bridge);
+ assert.deepEqual(bridge.listAttachments(SELF).map((a) => a.id), [shot.id]);
+
+ // The user deleting the chip removes the attachment too.
+ const theirReference = composer.state.references.find((r) => r.plugin?.id === theirs.id);
+ composer.state.text = composer.state.text.replace(theirReference.token, "");
+ bridge.publish(composer.handle);
+ assert.deepEqual(bridge.listAttachments(OTHER), []);
+});
+
+test("attachments.add refuses home, a full plugin, a failed stage and a session switch", async () => {
+ const { bridge } = quietBridge();
+ const data = new Uint8Array([1]).buffer;
+ const input = { name: "a.txt", mimeType: "text/plain", data };
+ const composer = fakeComposer({ sessionId: "" });
+ bridge.register(composer.handle);
+ await assert.rejects(bridge.addAttachment(SELF, input), refused("PLUGIN_ATTACHMENT_NO_SESSION"));
+ composer.state.sessionId = SID;
+
+ composer.state.stage = async () => {
+ throw new Error("disk full");
+ };
+ await assert.rejects(bridge.addAttachment(SELF, input), (error) => {
+ refused("PLUGIN_ATTACHMENT_FAILED")(error);
+ assert.equal(error.message, "disk full");
+ return true;
+ });
+
+ let release;
+ composer.state.stage = (sid, file) =>
+ new Promise((resolve) => {
+ release = () => resolve({ path: `/x/${file.name}`, name: file.name, kind: "file", mimeType: "text/plain", size: 1 });
+ });
+ const switched = bridge.addAttachment(SELF, input);
+ composer.state.sessionId = "s2";
+ release();
+ await assert.rejects(switched, refused("PLUGIN_ATTACHMENT_NO_SESSION"));
+ assert.deepEqual(composer.state.writes, [], "nothing lands in the other session's draft");
+
+ composer.state.sessionId = SID;
+ composer.state.stage = async (_sid, file) => ({ path: `/x/${file.name}`, name: file.name, kind: "image", mimeType: "image/png", size: 1 });
+ for (let i = 0; i < PLUGIN_ATTACHMENTS_MAX; i += 1) {
+ await bridge.addAttachment(SELF, { ...input, name: `p${i}.png` });
+ composer.render(bridge);
+ }
+ await assert.rejects(bridge.addAttachment(SELF, input), refused("PLUGIN_ATTACHMENT_LIMIT"));
+ await bridge.addAttachment(OTHER, input);
+});
diff --git a/apps/desktop/test/composer-plugin-marks.test.mjs b/apps/desktop/test/composer-plugin-marks.test.mjs
new file mode 100644
index 000000000..b2dc3d154
--- /dev/null
+++ b/apps/desktop/test/composer-plugin-marks.test.mjs
@@ -0,0 +1,133 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * Plugin marks in the composer draft (`docs/plugin-plan/ui/composer/`,
+ * `docs/plugin-plan/render/draft/`): a mark is a chip that shows its label
+ * and sends its text, one draft shows at most eight, and every further mark
+ * joins one host fold chip. Marks carry no path, so nothing path-shaped
+ * (labels, the workspace switch, the text-expand action) applies to them.
+ */
+const { PLUGIN_DRAFT_MAX_MARKS } = await import("@pi-desktop/plugin-sdk");
+const { serializeComposerFileReferences } = await import("@pi-desktop/shared");
+const { createFileReference, isEditableTextReference, isPluginMark } = await import(
+ "../src/features/chat/composer/editor.ts"
+);
+const { createPluginMark, foldLabel, liveChipReferences, placePluginMark } = await import(
+ "../src/features/chat/composer/plugins/plugin-marks.ts"
+);
+const {
+ draftFileReference,
+ sameDraftFileReference,
+ snapshotComposerDraft,
+ resetComposerDraftCache,
+} = await import("../src/lib/composer-draft-cache.ts");
+
+const SESSION = "session-1";
+const mark = (n, pluginId = "demo.lab") => ({ pluginId, label: `#${n}`, send: `Issue ${n}` });
+
+/** Accept `count` marks into an empty draft the way the composer does. */
+function acceptMarks(count, pluginId) {
+ let references = [];
+ let text = "";
+ for (let n = 1; n <= count; n += 1) {
+ const placed = placePluginMark(references, text, mark(n, pluginId), SESSION);
+ references = placed.references;
+ if (placed.token) text += `${placed.token} `;
+ }
+ return { references, text };
+}
+
+test("a mark shows its label as given and sends its text in place", () => {
+ const created = createPluginMark({ pluginId: "demo.lab", label: "src/a.ts", send: "S" }, SESSION);
+ assert.equal(created.name, "src/a.ts", "a label is never shortened like a path");
+ assert.equal(created.path, "");
+ assert.equal(created.sessionId, SESSION);
+ assert.equal(created.token.length, 1);
+ assert.deepEqual(created.plugin, { kind: "mark", pluginId: "demo.lab", send: "S" });
+ assert.equal(isPluginMark(created), true);
+ assert.equal(isEditableTextReference(created), false);
+
+ const labelled = createPluginMark({ pluginId: "demo.lab", label: "notes.txt", send: "S" }, SESSION);
+ assert.equal(isEditableTextReference(labelled), false, "a .txt label is no text file");
+ assert.equal(
+ serializeComposerFileReferences(`look ${created.token}now`, [created]),
+ "look S now",
+ );
+
+ const file = createFileReference("/tmp/a/notes.txt", undefined, SESSION);
+ assert.equal(file.name, "notes.txt");
+ assert.equal(isPluginMark(file), false);
+ const attachment = createFileReference("/tmp/a/b.txt", "b.txt", SESSION, {
+ plugin: { kind: "attachment", pluginId: "demo.lab", id: "att-1", size: 3 },
+ });
+ assert.equal(isPluginMark(attachment), false, "a plugin's attachment is a file");
+});
+
+test("up to eight marks are chips of their own; the ninth opens the fold", () => {
+ const { references, text } = acceptMarks(PLUGIN_DRAFT_MAX_MARKS + 1);
+ const live = liveChipReferences(references, text);
+ assert.equal(live.length, PLUGIN_DRAFT_MAX_MARKS + 1);
+ assert.deepEqual(
+ live.slice(0, PLUGIN_DRAFT_MAX_MARKS).map((reference) => reference.plugin.kind),
+ Array(PLUGIN_DRAFT_MAX_MARKS).fill("mark"),
+ );
+ const fold = live.at(-1);
+ assert.equal(fold.name, foldLabel(1));
+ assert.deepEqual(fold.plugin, { kind: "fold", pluginId: "demo.lab", send: "Issue 9", count: 1 });
+});
+
+test("further marks join the one fold, which keeps every text they send", () => {
+ const { references, text } = acceptMarks(PLUGIN_DRAFT_MAX_MARKS + 3);
+ const live = liveChipReferences(references, text);
+ assert.equal(live.length, PLUGIN_DRAFT_MAX_MARKS + 1, "one chip holds the overflow");
+ const fold = live.at(-1);
+ assert.equal(fold.name, "⧉ +3");
+ assert.equal(fold.plugin.count, 3);
+ assert.equal(fold.plugin.send, "Issue 9 Issue 10 Issue 11");
+ const sent = serializeComposerFileReferences(text, references);
+ for (let n = 1; n <= PLUGIN_DRAFT_MAX_MARKS + 3; n += 1) {
+ assert.match(sent, new RegExp(`Issue ${n}\\b`));
+ }
+});
+
+test("the limit counts marks of every plugin, and only chips still in the text", () => {
+ let { references, text } = acceptMarks(PLUGIN_DRAFT_MAX_MARKS - 1, "demo.lab");
+ let placed = placePluginMark(references, text, mark(99, "demo.other"), SESSION);
+ assert.equal(placed.references.at(-1).plugin.kind, "mark", "the eighth is a chip");
+ references = placed.references;
+ text += placed.token;
+ placed = placePluginMark(references, text, mark(100, "demo.other"), SESSION);
+ assert.equal(placed.references.at(-1).plugin.kind, "fold");
+ assert.equal(placed.references.at(-1).plugin.pluginId, "demo.other", "the fold names its first plugin");
+
+ // A chip the user deleted no longer counts, even with its reference around.
+ const withoutFirst = text.replace(references[0].token, "");
+ placed = placePluginMark(references, withoutFirst, mark(101), SESSION);
+ assert.equal(placed.references.at(-1).plugin.kind, "mark");
+});
+
+test("draft snapshots keep a reference's plugin part and compare it", () => {
+ resetComposerDraftCache();
+ const created = createPluginMark(mark(1), SESSION);
+ const snapshot = snapshotComposerDraft(`${created.token}`, [created], SESSION);
+ assert.deepEqual(snapshot.fileReferences, [
+ { path: "", name: "#1", kind: "file", token: created.token, plugin: created.plugin },
+ ]);
+ assert.deepEqual(draftFileReference(created), snapshot.fileReferences[0]);
+ assert.equal(sameDraftFileReference(created, snapshot.fileReferences[0]), true);
+ const resent = { ...created, plugin: { ...created.plugin, send: "other" } };
+ assert.equal(sameDraftFileReference(created, resent), false, "a different send is another draft");
+ const plain = { ...created, plugin: undefined };
+ assert.equal(sameDraftFileReference(created, plain), false);
+ const folded = { ...created, plugin: { kind: "fold", pluginId: "demo.lab", send: "a", count: 1 } };
+ assert.equal(sameDraftFileReference(folded, { ...folded, plugin: { ...folded.plugin, count: 2 } }), false);
+ const attachment = { kind: "attachment", pluginId: "demo.lab", id: "att-1", size: 3 };
+ assert.equal(
+ sameDraftFileReference({ ...plain, plugin: attachment }, { ...plain, plugin: { ...attachment } }),
+ true,
+ );
+});
diff --git a/apps/desktop/test/composer-plugin-triggers.test.mjs b/apps/desktop/test/composer-plugin-triggers.test.mjs
new file mode 100644
index 000000000..9ebdf5664
--- /dev/null
+++ b/apps/desktop/test/composer-plugin-triggers.test.mjs
@@ -0,0 +1,163 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * Plugin-owned composer triggers (`docs/plugin-plan/ui/composer/`): where a
+ * trigger is active in the draft, what of a plugin's answer the host keeps,
+ * and that a failing provider only ever collapses its own group.
+ */
+const {
+ PLUGIN_MARK_LABEL_MAX_CHARS,
+ PLUGIN_MARK_SEND_MAX_BYTES,
+ PLUGIN_TRIGGER_DETAIL_MAX_CHARS,
+ PLUGIN_TRIGGER_MAX_ITEMS,
+} = await import("@pi-desktop/plugin-sdk");
+const { askPluginTrigger, detectPluginTrigger, sanitizeTriggerItems } = await import(
+ "../src/features/chat/composer/plugins/plugin-triggers.ts"
+);
+
+const OWNED = new Set(["#"]);
+const CHIP = String.fromCharCode(0xe000);
+
+test("a trigger opens on an owned symbol at a line start or after whitespace", () => {
+ assert.deepEqual(detectPluginTrigger("#12", 3, OWNED), {
+ trigger: "#",
+ query: "12",
+ tokenStart: 0,
+ tokenEnd: 3,
+ });
+ assert.deepEqual(detectPluginTrigger("fix #", 5, OWNED), {
+ trigger: "#",
+ query: "",
+ tokenStart: 4,
+ tokenEnd: 5,
+ });
+ assert.equal(detectPluginTrigger("line\n#ab", 8, OWNED)?.tokenStart, 5);
+ // The query runs to the caret, not to the end of the word.
+ assert.equal(detectPluginTrigger("#abcdef", 3, OWNED)?.query, "ab");
+});
+
+test("a full-width symbol counts as its ASCII trigger", () => {
+ const match = detectPluginTrigger("\uFF03bug", 4, OWNED);
+ assert.equal(match?.trigger, "#");
+ assert.equal(match?.query, "bug");
+});
+
+test("no trigger inside a word, for an unowned symbol, or across a chip", () => {
+ assert.equal(detectPluginTrigger("issue#12", 8, OWNED), null);
+ assert.equal(detectPluginTrigger("@me", 3, OWNED), null);
+ assert.equal(detectPluginTrigger("#12", 3, new Set()), null);
+ assert.equal(detectPluginTrigger(`#a${CHIP}b`, 4, OWNED), null);
+ assert.equal(detectPluginTrigger("#a\uFFFC", 3, OWNED), null);
+ assert.equal(detectPluginTrigger(`${CHIP}#a`, 3, OWNED), null);
+ assert.equal(detectPluginTrigger("# a", 3, OWNED), null);
+ assert.equal(detectPluginTrigger("#a", 0, OWNED), null);
+ assert.equal(detectPluginTrigger("#a", 9, OWNED), null);
+});
+
+test("an answer keeps its good items and drops each one breaking a limit", () => {
+ const rows = sanitizeTriggerItems([
+ { label: "Plain" },
+ { label: "Sent", send: "Issue 7", detail: "open" },
+ { label: "" },
+ { label: " " },
+ { label: 42 },
+ null,
+ "text",
+ { label: "x".repeat(PLUGIN_MARK_LABEL_MAX_CHARS + 1) },
+ { label: "two\nlines" },
+ { label: "sep\u2028arator" },
+ { label: `chip${CHIP}` },
+ { label: "mark\uFFFC" },
+ { label: "empty send", send: " " },
+ { label: "bad send", send: 7 },
+ { label: "chip send", send: `a${CHIP}` },
+ { label: "huge send", send: "\u00E9".repeat(PLUGIN_MARK_SEND_MAX_BYTES / 2 + 1) },
+ { label: "bad detail", detail: 3 },
+ { label: "long detail", detail: "d".repeat(PLUGIN_TRIGGER_DETAIL_MAX_CHARS + 1) },
+ { label: "x".repeat(PLUGIN_MARK_LABEL_MAX_CHARS), send: "a\nb" },
+ ]);
+ assert.deepEqual(rows, [
+ { label: "Plain", send: "Plain" },
+ { label: "Sent", send: "Issue 7", detail: "open" },
+ { label: "x".repeat(PLUGIN_MARK_LABEL_MAX_CHARS), send: "a\nb" },
+ ]);
+});
+
+test("an answer is cut at the item cap, and no array is no answer", () => {
+ const many = Array.from({ length: PLUGIN_TRIGGER_MAX_ITEMS + 5 }, (_, i) => ({ label: `#${i}` }));
+ const rows = sanitizeTriggerItems([{ label: "" }, ...many]);
+ assert.equal(rows.length, PLUGIN_TRIGGER_MAX_ITEMS);
+ assert.equal(rows[0].label, "#0");
+ assert.equal(sanitizeTriggerItems(undefined), null);
+ assert.equal(sanitizeTriggerItems({ length: 1, 0: { label: "a" } }), null);
+ assert.deepEqual(sanitizeTriggerItems([]), []);
+});
+
+function quietly(run) {
+ const warn = console.warn;
+ const warnings = [];
+ console.warn = (...args) => warnings.push(args);
+ return run().finally(() => {
+ console.warn = warn;
+ }).then((value) => ({ value, warnings }));
+}
+
+test("a provider is asked with the trigger and query, sync or async", async () => {
+ const asked = [];
+ const sync = await askPluginTrigger(
+ (query) => {
+ asked.push(query);
+ return [{ label: "a" }];
+ },
+ { trigger: "#", query: "q", tokenStart: 0, tokenEnd: 2 },
+ "demo.lab",
+ );
+ assert.deepEqual(asked, [{ trigger: "#", query: "q" }]);
+ assert.deepEqual(sync, [{ label: "a", send: "a" }]);
+ const later = await askPluginTrigger(
+ async () => [{ label: "b", send: "B" }],
+ { trigger: "#", query: "" },
+ "demo.lab",
+ );
+ assert.deepEqual(later, [{ label: "b", send: "B" }]);
+});
+
+test("a throwing, rejecting, silent or malformed provider collapses to null and is logged", async () => {
+ const match = { trigger: "#", query: "" };
+ const cases = [
+ () => {
+ throw new Error("boom");
+ },
+ () => Promise.reject(new Error("nope")),
+ () => new Promise(() => {}),
+ () => ({ label: "not a list" }),
+ ];
+ for (const provider of cases) {
+ const { value, warnings } = await quietly(() => askPluginTrigger(provider, match, "demo.lab", 20));
+ assert.equal(value, null);
+ assert.equal(warnings.length, 1);
+ assert.match(String(warnings[0][0]), /demo\.lab composerTrigger failed/);
+ }
+});
+
+test("an answer after the timeout is ignored", async () => {
+ let answer;
+ const { value } = await quietly(() =>
+ askPluginTrigger(
+ () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ { trigger: "#", query: "" },
+ "demo.lab",
+ 10,
+ ),
+ );
+ assert.equal(value, null);
+ answer([{ label: "late" }]);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+});
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/README.md b/apps/desktop/test/e2e/plugin-ui-slots/README.md
index 6c406fbed..36bf344b4 100644
--- a/apps/desktop/test/e2e/plugin-ui-slots/README.md
+++ b/apps/desktop/test/e2e/plugin-ui-slots/README.md
@@ -16,19 +16,34 @@ pnpm test:e2e:plugin-ui-slots
| `scripts/e2e-plugin-ui-slots.mjs` | Runner: isolated data/home/profile, seed, Electron with MCP control and a CDP port, cleanup |
| `stub-model.mjs` | Stub model; the prompt names the scenario (`lab: probe <ok\|fail\|crash\|slow>`, `lab: chart <crash\|tall>`, `lab: gate`) |
| `seed.mjs` | Provider row for the stub and `plugins.loadDev` of a copy of the lab, through host-core JSON-RPC |
-| `clients.mjs` | MCP control client (sessions, prompts, turn status) and a CDP renderer client |
+| `clients.mjs` | MCP control client (sessions, prompts, turn status) and a CDP renderer client, with trusted mouse and text input |
| `drive.mjs` | The scenarios and their checks |
+| `composer-draft.mjs` | The composer draft, `#` trigger and attachment scenarios |
Covered behavior (`E2E-PLUGIN-ui-slots-*` in the E2E test plan):
- every slot mounts its sample for the open session: `userAction`,
`assistantAction` (fourth right item in the ⋯ menu), stacked `entryExtra`,
- `toolCard`, `blockRenderer`, `composerControl`
+ `toolCard`, `blockRenderer`, `composerControl`; the lab's toolbar controls
+ fit their slots whole (a control that does not is cut at its own edge)
- the plugin's injected sheet is scoped to its own mounts
- ⋯ menu opens, closes on Escape (focus returns to ⋯) and on an outside
press, stays open on an inside press, and runs the folded item
- `plugin.call` round trips, a plugin error code passing through, and the
2s `PLUGIN_CALL_TIMEOUT`; `composer.insertText` from every slot
+- `composerTrigger`: typing `#caret` lists the lab's matching row, and
+ picking it leaves the plugin's mark chip in place of the typed token
+- the draft lab, a panel in the lab's own layer docked above the composer
+ (which stays reachable), closed by its ✕
+- the draft followed through `pi.composer.subscribeDraft`; `composer.replaceDraft`
+ from a trusted click rewrites it with marks kept, one stamp and focus left
+ where it was, while a synthetic click or a write started after the click
+ is `PLUGIN_DRAFT_REMOTE`; `composer.readDraft` answers the followed
+ generation
+- `attachments.add` of a note (a chip, focus left alone) and an image (the
+ image tray), a path refused as `PLUGIN_ATTACHMENT_REFERENCE_REFUSED`,
+ `attachments.list`, and `attachments.remove` down to
+ `PLUGIN_ATTACHMENT_NOT_FOUND`
- `entryExtra` collapsed clamp and the host expand toggle
- a crashing item, block or control is contained to itself
- `toolCard`: a failed call as `toolError`, a throwing card falling back to
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs b/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs
index 47acb89c1..ca152cc45 100644
--- a/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs
+++ b/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs
@@ -115,6 +115,41 @@ export async function connectRenderer(port) {
}
throw new Error(`timed out waiting for ${label} (last ${JSON.stringify(last)})`);
},
+ /**
+ * A person's click on the first element `selector` matches: CDP mouse
+ * input at its center, so the page sees trusted events. Waits a moment
+ * for the element to show and settle (a popup still easing in), then
+ * throws when it is missing or something else is on top of it.
+ */
+ async click(selector) {
+ const locate = () => run((selector) => {
+ const node = document.querySelector(selector);
+ if (!node) return { missing: true };
+ node.scrollIntoView({ block: "nearest" });
+ const box = node.getBoundingClientRect();
+ const x = box.left + box.width / 2;
+ const y = box.top + box.height / 2;
+ const hit = document.elementFromPoint(x, y);
+ const covered = !(hit && node.contains(hit));
+ return { x, y, covered, by: covered ? (hit?.outerHTML.slice(0, 80) ?? "nothing") : null };
+ }, selector);
+ const deadline = Date.now() + 2_000;
+ let point = await locate();
+ while ((point.missing || point.covered) && Date.now() < deadline) {
+ await sleep(50);
+ point = await locate();
+ }
+ if (point.missing || point.covered) {
+ throw new Error(`cannot click ${selector}: ${point.missing ? "missing" : `covered by ${point.by}`}`);
+ }
+ for (const type of ["mousePressed", "mouseReleased"]) {
+ await call("Input.dispatchMouseEvent", { type, x: point.x, y: point.y, button: "left", clickCount: 1 });
+ }
+ },
+ /** A person's typing into the focused element. */
+ async type(text) {
+ await call("Input.insertText", { text });
+ },
async screenshot() {
return (await call("Page.captureScreenshot", { format: "png" })).data;
},
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjs b/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjs
new file mode 100644
index 000000000..8e7dd43b3
--- /dev/null
+++ b/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjs
@@ -0,0 +1,211 @@
+// The lab's composer samples beyond the toolbar: the `#` trigger, and the
+// draft lab panel, where the draft is rewritten and attachments are staged
+// into the open session. A rewrite needs a person's input, so these steps
+// click and type through CDP input (`renderer.click`, `renderer.type`); a
+// page-side `element.click()` is synthetic, which is what a remote write
+// looks like.
+
+const button = (lab, name) => `[data-lab="${lab}"] [data-lab-button="${name}"]`;
+
+/** What the composer shows: its text, chips by kind, and the image tray. */
+function composerView() {
+ const input = document.querySelector(".composer-input");
+ const chips = [...(input?.querySelectorAll(".composer-chip") ?? [])].map((chip) => ({
+ mark: chip.dataset.pluginMark ?? null,
+ name: chip.querySelector(".composer-chip-name")?.textContent ?? "",
+ }));
+ const images = [...document.querySelectorAll(".composer-image-attachment-open")].map(
+ (open) => open.getAttribute("aria-label")?.split(" — ")[0] ?? "",
+ );
+ return {
+ text: input ? (input.value ?? input.textContent) : null,
+ focused: Boolean(input) && document.activeElement === input,
+ chips,
+ images,
+ follows: document.querySelector("[data-lab-draft]")?.getAttribute("data-lab-draft") ?? null,
+ };
+}
+
+export async function driveComposerDraft({ renderer, check }) {
+ const page = renderer.run;
+ // A sample's outcome once `accept(outcome)` holds; `accept` runs in the
+ // page, so it closes over nothing of this module.
+ const outcome = (lab, label, accept) =>
+ renderer
+ .until(
+ `(lab) => { const out = window.__labE2E.result(document, lab); return out && (${accept})(out) ? out : null; }`,
+ lab,
+ label,
+ 5_000,
+ )
+ .catch((error) => ({ error: error.message }));
+ const view = () => page(composerView);
+ const synthetic = (lab, name) => page((selector) => {
+ document.querySelector(selector)?.click();
+ return true;
+ }, button(lab, name));
+
+ const DRAFT = "layer:draft";
+ const ATTACH = "layer:attach";
+
+ // Every toolbar control, the lab's with their outcomes showing, fits its
+ // slot whole: nothing is cut at a slot's edge.
+ const cut = await page(() =>
+ [...document.querySelectorAll('.pi-plugin-slot[data-pi-slot="composerControl"]')]
+ .filter((slot) => slot.scrollWidth > slot.clientWidth + 1)
+ .map((slot) => {
+ const name = slot.firstElementChild?.getAttribute("data-lab") ?? slot.getAttribute("data-pi-plugin");
+ return `${name} ${slot.scrollWidth}>${slot.clientWidth}`;
+ }),
+ );
+ check("the lab's toolbar controls fit the toolbar whole", cut.length === 0, JSON.stringify(cut));
+
+ const start = await view();
+ check("the lab follows the live draft", /^\d+$/.test(start.follows ?? ""), JSON.stringify(start.follows));
+
+ // --- the `#` trigger ------------------------------------------------------
+ await page(() => {
+ const input = document.querySelector(".composer-input");
+ input.focus();
+ const range = document.createRange();
+ range.selectNodeContents(input);
+ range.collapse(false);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ return true;
+ });
+ await renderer.type(" #caret");
+ const rows = await renderer
+ .until(
+ () => {
+ const names = [...document.querySelectorAll(".composer-ac-list .composer-ac-name")].map((name) => name.textContent);
+ return names.length ? names : null;
+ },
+ null,
+ "the lab's # rows",
+ 5_000,
+ )
+ .catch((error) => ({ error: error.message }));
+ check("typing # lists the lab's matching issues", Array.isArray(rows) && rows.join() === "#7", JSON.stringify(rows));
+ await renderer.click('.composer-ac-list [data-ac-index="0"]');
+ const marked = await renderer
+ .until(
+ `() => { const v = (${composerView})(); return v.chips.some((chip) => chip.mark === "mark" && chip.name === "#7") ? v : null; }`,
+ null,
+ "the #7 mark",
+ 5_000,
+ )
+ .catch((error) => ({ error: error.message }));
+ check(
+ "picking a row puts the plugin's mark in place of the typed token",
+ Boolean(marked.text) && !marked.text.includes("#caret"),
+ JSON.stringify(marked),
+ );
+
+ // --- the draft rewritten ---------------------------------------------------
+ await synthetic("composerControl:draft", "draft-panel");
+ const docked = await renderer
+ .until(
+ () => {
+ const panel = document.querySelector('[data-lab="layer:composer"] .p-dialog');
+ const input = document.querySelector(".composer-input");
+ if (!panel || !input) return null;
+ const box = panel.getBoundingClientRect();
+ const field = input.getBoundingClientRect();
+ const hit = document.elementFromPoint(field.left + 8, field.top + 8);
+ return {
+ z: Number(panel.closest("[data-pi-layer]")?.style.zIndex),
+ above: box.bottom <= field.top,
+ composerReachable: Boolean(hit && input.contains(hit)),
+ };
+ },
+ null,
+ "the draft lab panel",
+ 5_000,
+ )
+ .catch((error) => ({ error: error.message }));
+ check(
+ "the draft lab opens in its own layer, docked clear of the composer",
+ docked.z >= 600 && docked.above && docked.composerReachable,
+ JSON.stringify(docked),
+ );
+ const before = await view();
+ await renderer.click(button(DRAFT, "draft-polish"));
+ const polished = await outcome(DRAFT, "the polish outcome", (out) => out.text.startsWith("polished g"));
+ const afterPolish = await view();
+ const stamps = (state) => state.chips.filter((chip) => chip.mark === "mark" && chip.name === "lab ✓").length;
+ check(
+ "a click on Polish rewrites the draft it followed, marks kept in place",
+ polished.status === "ok" && stamps(afterPolish) === 1 && afterPolish.chips.some((chip) => chip.name === "#7") &&
+ !/ {2}/.test(afterPolish.text) && afterPolish.follows !== before.follows && !afterPolish.focused,
+ JSON.stringify({ polished, afterPolish }),
+ );
+ await renderer.click(button(DRAFT, "draft-polish"));
+ const again = await outcome(DRAFT, "the second polish", (out) => out.status === "ok" && out.text !== polished.text);
+ check("polishing again keeps a single stamp", stamps(await view()) === 1, JSON.stringify(again));
+
+ const unchanged = (await view()).text;
+ await renderer.click(button(DRAFT, "draft-polish-late"));
+ const late = await outcome(DRAFT, "the late polish", (out) => out.status === "error");
+ check(
+ "a rewrite that starts after the click is refused as remote",
+ late.text === "PLUGIN_DRAFT_REMOTE" && (await view()).text === unchanged,
+ JSON.stringify(late),
+ );
+ await synthetic(DRAFT, "draft-read");
+ const read = await outcome(DRAFT, "the read outcome", (out) => out.status === "ok");
+ check("composer.readDraft answers with the followed generation", read.text === `read g${(await view()).follows}`, JSON.stringify(read));
+ await synthetic(DRAFT, "draft-polish");
+ const remote = await outcome(DRAFT, "the synthetic polish", (out) => out.status === "error");
+ check(
+ "a synthetic click is no gesture: the rewrite is refused",
+ remote.text === "PLUGIN_DRAFT_REMOTE" && (await view()).text === unchanged,
+ JSON.stringify(remote),
+ );
+
+ // --- attachments ------------------------------------------------------------
+ const step = async (name, label, accept) => {
+ await synthetic(ATTACH, name);
+ return outcome(ATTACH, label, accept);
+ };
+ const note = await step("attach-note", "the note", (out) => out.text === "note attached" || out.status === "error");
+ const withNote = await view();
+ check(
+ "a text attachment lands as a chip in the draft",
+ note.status === "ok" && withNote.chips.some((chip) => chip.mark === null && chip.name === "lab-note.md") && !withNote.focused,
+ JSON.stringify({ note, chips: withNote.chips }),
+ );
+ const image = await step("attach-image", "the image", (out) => out.text === "image attached" || out.status === "error");
+ const withImage = await view();
+ check(
+ "an image attachment joins the draft's images, not its text",
+ image.status === "ok" && withImage.images.includes("lab-dot.png") && withImage.chips.length === withNote.chips.length,
+ JSON.stringify({ image, images: withImage.images }),
+ );
+ const path = await step("attach-path", "the path", (out) => out.status === "error");
+ check("a path is refused, not read", path.text === "PLUGIN_ATTACHMENT_REFERENCE_REFUSED", JSON.stringify(path));
+ const listed = await step("attach-list", "the list", (out) => out.status === "ok");
+ check("attachments.list names the plugin's attachments", listed.text === "2: lab-note.md, lab-dot.png", JSON.stringify(listed));
+ const removed = await step("attach-remove", "the image removed", (out) => out.status === "ok");
+ const withoutImage = await view();
+ check("attachments.remove takes the image out of the draft", removed.text === "removed" && !withoutImage.images.includes("lab-dot.png"), JSON.stringify(withoutImage.images));
+ const one = await step("attach-list", "the list of one", (out) => out.status === "ok" && out.text !== "removed");
+ await step("attach-remove", "the note removed", (out) => out.status === "ok" && out.text !== one.text);
+ const empty = await renderer
+ .until(
+ `() => { const v = (${composerView})(); return v.chips.some((chip) => chip.name === "lab-note.md") ? null : v; }`,
+ null,
+ "the note chip gone",
+ 5_000,
+ )
+ .catch((error) => ({ error: error.message }));
+ check("removing the note takes its chip with it", one.text === "1: lab-note.md" && Array.isArray(empty.chips), JSON.stringify({ one, chips: empty.chips }));
+ const none = await step("attach-remove", "nothing to remove", (out) => out.status === "error");
+ check("an unknown attachment id is refused", none.text === "PLUGIN_ATTACHMENT_NOT_FOUND", JSON.stringify(none));
+
+ await synthetic("layer:composer", "draft-close");
+ const closed = await renderer
+ .until(() => (document.querySelector('[data-lab="layer:composer"], #pi-plugin-layers') ? null : true), null, "the draft lab closed", 5_000)
+ .catch((error) => ({ error: error.message }));
+ check("the draft lab's ✕ closes its layer", closed === true, JSON.stringify(closed));
+}
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs b/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
index f50fe5123..6a8428db0 100644
--- a/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
+++ b/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
@@ -1,6 +1,7 @@
// Drives the UI Slots Lab through the real app: prompts go through the MCP
// control plane, and every assertion reads the renderer DOM the host slots
// draw into, by the lab's `data-lab="<slot>[:<side>]"` markers.
+import { driveComposerDraft } from "./composer-draft.mjs";
import { PROBE_TOOL } from "./stub-model.mjs";
const LAB = "lab.ui-slots";
@@ -147,7 +148,13 @@ export async function drive({ control, renderer, check, project }) {
);
check(
"composerControl samples sit on both toolbar sides",
- sameSet(layout.toolbar, ["composerControl:left", "composerControl:right", "composerControl:crash", "composerControl:layers"]),
+ sameSet(layout.toolbar, [
+ "composerControl:left",
+ "composerControl:draft",
+ "composerControl:right",
+ "composerControl:crash",
+ "composerControl:layers",
+ ]),
layout.toolbar.join(","),
);
check("every sample was mounted for the open session", layout.sessions.length === 1 && layout.sessions[0] === sessionId, layout.sessions.join(","));
@@ -267,7 +274,8 @@ export async function drive({ control, renderer, check, project }) {
);
await clickIn(null, "composerControl:right", "echo");
const composerEcho = await settled(null, "composerControl:right", "composer echo");
- check("a composer control round-trips plugin.call", composerEcho.text === "echo ✓", JSON.stringify(composerEcho));
+ check("a composer control round-trips plugin.call", composerEcho.text === "✓", JSON.stringify(composerEcho));
+ await driveComposerDraft({ renderer, check });
// --- entryExtra height ------------------------------------------------------
const entryBlock = (action) =>
@@ -337,6 +345,7 @@ export async function drive({ control, renderer, check, project }) {
"assistantAction:refuse",
"entryExtra:notes",
"composerControl:left",
+ "composerControl:draft",
"composerControl:right",
"composerControl:layers",
];
diff --git a/apps/desktop/test/plugin-renderer-dispatch.test.mjs b/apps/desktop/test/plugin-renderer-dispatch.test.mjs
index cd5e55ffc..acda84224 100644
--- a/apps/desktop/test/plugin-renderer-dispatch.test.mjs
+++ b/apps/desktop/test/plugin-renderer-dispatch.test.mjs
@@ -10,14 +10,17 @@ register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
* cuts the channel off, answers in flight included.
*/
const { createDispatchChannel } = await import("../src/plugins/renderer-host/dispatch.ts");
+const { isUserGesture } = await import("../src/plugins/renderer-host/composer-actions.ts");
const { PluginRendererError } = await import("../src/plugins/renderer-error.ts");
-const { registerComposerInsert, resetComposerInsertBridge } = await import(
- "../src/features/chat/composer/insert-bridge.ts"
+const { composerDraftBridge } = await import(
+ "../src/features/chat/composer/plugins/draft-bridge.ts"
);
const { IPC } = await import("@pi-desktop/shared");
+const { PLUGIN_RENDERER_ACTIONS } = await import("@pi-desktop/plugin-sdk");
const PLUGIN = "demo.lab";
-const BOTH = ["plugin.call", "composer.insertText"];
+const ALL = [...PLUGIN_RENDERER_ACTIONS];
+const MARK = "\uFFFC";
function rejectsWith(code) {
return (error) => {
@@ -28,21 +31,30 @@ function rejectsWith(code) {
}
/** Routes that record what reached them. */
-function fakeRoutes({ call = async () => ({ ok: true }), insert = () => true } = {}) {
+function fakeRoutes({ call = async () => ({ ok: true }), composer = {}, gesture = () => false } = {}) {
const calls = [];
- const inserts = [];
+ const reached = [];
+ const answer = (name, fallback) => (...args) => {
+ reached.push([name, ...args]);
+ return (composer[name] ?? fallback)(...args);
+ };
return {
calls,
- inserts,
+ reached,
routes: {
pluginCall: (pluginId, method, args) => {
calls.push({ pluginId, method, args });
return call(pluginId, method, args);
},
- insertText: (text) => {
- inserts.push(text);
- return insert(text);
+ composer: {
+ insertText: answer("insertText", () => ({ ok: true, generation: 1 })),
+ readDraft: answer("readDraft", () => ({ text: "", marks: [], generation: 1 })),
+ replaceDraft: answer("replaceDraft", () => ({ ok: true, generation: 2 })),
+ addAttachment: answer("addAttachment", async () => ({ id: "a1" })),
+ listAttachments: answer("listAttachments", () => []),
+ removeAttachment: answer("removeAttachment", () => ({ ok: true })),
},
+ userGesture: gesture,
},
};
}
@@ -58,17 +70,24 @@ function deferred() {
}
test("a word outside the vocabulary or the manifest is refused before any route runs", async () => {
- const { routes, calls, inserts } = fakeRoutes();
+ const { routes, calls, reached } = fakeRoutes();
const { dispatch } = createDispatchChannel(PLUGIN, ["plugin.call"], routes);
const refused = dispatch("composer.insertText", { text: "hi" });
assert.ok(refused instanceof Promise, "refusals reject; dispatch never throws synchronously");
await assert.rejects(refused, rejectsWith("PLUGIN_ACTION_UNDECLARED"));
+ for (const action of ALL.filter((word) => word !== "plugin.call")) {
+ await assert.rejects(dispatch(action, {}), rejectsWith("PLUGIN_ACTION_UNDECLARED"), action);
+ }
await assert.rejects(dispatch("ui.toast", { text: "hi" }), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
+ await assert.rejects(
+ dispatch("composer.acceptTriggerItem", {}),
+ rejectsWith("PLUGIN_ACTION_UNKNOWN"),
+ );
await assert.rejects(dispatch(42, {}), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
await assert.rejects(dispatch(undefined, {}), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
assert.deepEqual(calls, []);
- assert.deepEqual(inserts, []);
+ assert.deepEqual(reached, []);
// Declaring a word the host does not implement grants nothing.
const { dispatch: widened } = createDispatchChannel(PLUGIN, ["ui.toast"], routes);
@@ -76,51 +95,236 @@ test("a word outside the vocabulary or the manifest is refused before any route
});
test("a payload must be an object of the word's shape", async () => {
- const { routes, calls, inserts } = fakeRoutes();
- const { dispatch } = createDispatchChannel(PLUGIN, BOTH, routes);
- for (const payload of [undefined, null, "ping", [], [{ method: "ping" }], {}, { method: "" }, { method: 3 }]) {
- await assert.rejects(
- dispatch("plugin.call", payload),
- rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
- `plugin.call ${JSON.stringify(payload)}`,
- );
- }
- for (const payload of [undefined, "hi", ["hi"], {}, { text: "" }, { text: 3 }, { text: ["hi"] }]) {
- await assert.rejects(
- dispatch("composer.insertText", payload),
- rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
- `composer.insertText ${JSON.stringify(payload)}`,
- );
+ const { routes, calls, reached } = fakeRoutes();
+ const { dispatch } = createDispatchChannel(PLUGIN, ALL, routes);
+ const invalid = {
+ "plugin.call": [undefined, null, "ping", [], [{ method: "ping" }], {}, { method: "" }, { method: 3 }],
+ "composer.insertText": [undefined, "hi", ["hi"], {}, { text: "" }, { text: 3 }, { text: ["hi"] }],
+ "composer.readDraft": [undefined, null, "draft", []],
+ "composer.replaceDraft": [
+ {},
+ { text: "a" },
+ { expectedGeneration: -1, text: "a" },
+ { expectedGeneration: 1.5, text: "a" },
+ { expectedGeneration: "1", text: "a" },
+ { expectedGeneration: 2 ** 53, text: "a" },
+ { expectedGeneration: 1 },
+ { expectedGeneration: 1, text: 3 },
+ { expectedGeneration: 1, text: "a", extra: true },
+ { expectedGeneration: 1, text: "a", marks: {} },
+ { expectedGeneration: 1, text: MARK },
+ { expectedGeneration: 1, text: "a", marks: [{ id: "m" }] },
+ { expectedGeneration: 1, text: MARK, marks: [null] },
+ { expectedGeneration: 1, text: MARK, marks: ["m"] },
+ { expectedGeneration: 1, text: MARK, marks: [{ id: "" }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ id: 3 }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ id: "m", label: "x" }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ label: "" }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ label: "a\nb" }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ label: "a", send: " " }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ label: "a", detail: "d" }] },
+ { expectedGeneration: 1, text: MARK, marks: [{ label: "x".repeat(65) }] },
+ ],
+ "attachments.add": [
+ {},
+ { name: "a.txt", mimeType: "text/plain" },
+ { name: "a.txt", mimeType: "text/plain", content: 3 },
+ { name: "a.txt", mimeType: "text/plain", content: [1, 2] },
+ { name: "a.txt", mimeType: "text/plain", content: "hi", extra: 1 },
+ { name: "a.txt", mimeType: "text/plain", token: "t" },
+ { name: "a.txt", mimeType: "text/plain", content: "hi", token: "t" },
+ { name: "noext", mimeType: "text/plain", content: "hi" },
+ { name: ".txt", mimeType: "text/plain", content: "hi" },
+ { name: "dir/a.txt", mimeType: "text/plain", content: "hi" },
+ { name: "dir\\a.txt", mimeType: "text/plain", content: "hi" },
+ { name: "a\n.txt", mimeType: "text/plain", content: "hi" },
+ { name: `${"a".repeat(252)}.txt`, mimeType: "text/plain", content: "hi" },
+ { name: 3, mimeType: "text/plain", content: "hi" },
+ { name: "a.txt", mimeType: "text", content: "hi" },
+ { name: "a.txt", mimeType: "text/plain; charset=utf-8", content: "hi" },
+ { name: "a.txt", content: "hi" },
+ ],
+ "attachments.list": [undefined, []],
+ "attachments.remove": [undefined, {}, { id: "" }, { id: 3 }],
+ };
+ for (const [action, payloads] of Object.entries(invalid)) {
+ for (const payload of payloads) {
+ await assert.rejects(
+ dispatch(action, payload),
+ rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
+ `${action} ${JSON.stringify(payload)}`,
+ );
+ }
}
assert.deepEqual(calls, []);
- assert.deepEqual(inserts, []);
+ assert.deepEqual(reached, []);
});
-test("composer.insertText takes up to 32KB of UTF-8 and answers ok, or NO_COMPOSER", async () => {
- const { routes, inserts } = fakeRoutes();
+test("composer.insertText takes up to 32KB of UTF-8 and answers with the bridge's result", async () => {
+ const { routes, reached } = fakeRoutes({
+ composer: { insertText: () => ({ ok: true, generation: 7 }) },
+ });
const { dispatch } = createDispatchChannel(PLUGIN, ["composer.insertText"], routes);
- assert.deepEqual(await dispatch("composer.insertText", { text: "a".repeat(32 * 1024) }), { ok: true });
- // "é" is two bytes: the ceiling counts bytes, not characters.
- assert.deepEqual(await dispatch("composer.insertText", { text: "é".repeat(16 * 1024) }), { ok: true });
+ assert.deepEqual(await dispatch("composer.insertText", { text: "a".repeat(32 * 1024) }), {
+ ok: true,
+ generation: 7,
+ });
+ // "\u00E9" is two bytes: the ceiling counts bytes, not characters.
+ await dispatch("composer.insertText", { text: "\u00E9".repeat(16 * 1024) });
await assert.rejects(
- dispatch("composer.insertText", { text: "é".repeat(16 * 1024 + 1) }),
+ dispatch("composer.insertText", { text: "\u00E9".repeat(16 * 1024 + 1) }),
rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
);
assert.deepEqual(
- inserts.map((text) => text.length),
- [32 * 1024, 16 * 1024],
+ reached.map(([name, text]) => [name, text.length]),
+ [
+ ["insertText", 32 * 1024],
+ ["insertText", 16 * 1024],
+ ],
"only accepted text reaches the composer, unchanged",
);
+});
- const { routes: noComposer } = fakeRoutes({ insert: () => false });
- const { dispatch: unmounted } = createDispatchChannel(PLUGIN, ["composer.insertText"], noComposer);
+test("a refusal of the composer bridge rejects the dispatch as it was thrown", async () => {
+ const refusal = new PluginRendererError("PLUGIN_ACTION_NO_COMPOSER", "no composer takes input");
+ const { routes } = fakeRoutes({
+ composer: {
+ readDraft: () => {
+ throw refusal;
+ },
+ addAttachment: async () => {
+ throw new PluginRendererError("PLUGIN_ATTACHMENT_FAILED", "disk full");
+ },
+ },
+ });
+ const { dispatch } = createDispatchChannel(PLUGIN, ALL, routes);
+ const read = dispatch("composer.readDraft", {});
+ assert.ok(read instanceof Promise, "a throwing route still only rejects");
+ await assert.rejects(read, (error) => error === refusal);
await assert.rejects(
- unmounted("composer.insertText", { text: "hi" }),
- rejectsWith("PLUGIN_ACTION_NO_COMPOSER"),
+ dispatch("attachments.add", { name: "a.txt", mimeType: "text/plain", content: "hi" }),
+ rejectsWith("PLUGIN_ATTACHMENT_FAILED"),
);
});
+test("the read and list words reach the bridge with the plugin's own id", async () => {
+ const { routes, reached } = fakeRoutes({
+ composer: {
+ readDraft: (pluginId) => ({ text: `for ${pluginId}`, marks: [], generation: 3 }),
+ listAttachments: () => [{ id: "a1", name: "a.txt", mimeType: "text/plain", size: 2 }],
+ },
+ });
+ const { dispatch } = createDispatchChannel(PLUGIN, ALL, routes);
+ assert.deepEqual(await dispatch("composer.readDraft", {}), {
+ text: `for ${PLUGIN}`,
+ marks: [],
+ generation: 3,
+ });
+ assert.equal((await dispatch("attachments.list", {})).length, 1);
+ assert.deepEqual(await dispatch("attachments.remove", { id: "a1" }), { ok: true });
+ assert.deepEqual(reached, [
+ ["readDraft", PLUGIN],
+ ["listAttachments", PLUGIN],
+ ["removeAttachment", PLUGIN, "a1"],
+ ]);
+});
+
+test("composer.replaceDraft hands the bridge checked marks and the gesture at the call", async () => {
+ let gesture = true;
+ const { routes, reached } = fakeRoutes({ gesture: () => gesture });
+ const { dispatch } = createDispatchChannel(PLUGIN, ["composer.replaceDraft"], routes);
+
+ const pending = dispatch("composer.replaceDraft", {
+ expectedGeneration: 4,
+ text: `a${MARK}b${MARK}`,
+ marks: [{ id: "composer-file-1" }, { label: "Issue 7" }],
+ });
+ // The event is over by the time anything after the call runs.
+ gesture = false;
+ assert.deepEqual(await pending, { ok: true, generation: 2 });
+ await dispatch("composer.replaceDraft", { expectedGeneration: 5, text: "plain" });
+ assert.deepEqual(reached, [
+ [
+ "replaceDraft",
+ PLUGIN,
+ {
+ expectedGeneration: 4,
+ text: `a${MARK}b${MARK}`,
+ marks: [{ id: "composer-file-1" }, { label: "Issue 7", send: "Issue 7" }],
+ },
+ true,
+ ],
+ ["replaceDraft", PLUGIN, { expectedGeneration: 5, text: "plain", marks: [] }, false],
+ ]);
+
+ const big = "a".repeat(256 * 1024 + 1);
+ await assert.rejects(
+ dispatch("composer.replaceDraft", { expectedGeneration: 1, text: big }),
+ rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
+ );
+ await dispatch("composer.replaceDraft", { expectedGeneration: 1, text: big.slice(1) });
+});
+
+test("attachments.add takes the content itself, copied, and refuses a path or URL", async () => {
+ const { routes, reached } = fakeRoutes();
+ const { dispatch } = createDispatchChannel(PLUGIN, ["attachments.add"], routes);
+ const add = (content, name = "a.txt", mimeType = "text/plain") =>
+ dispatch("attachments.add", { name, mimeType, content });
+ const bytesOf = (index) => [...new Uint8Array(reached[index][2].data)];
+
+ assert.deepEqual(await add("h\u00E9"), { id: "a1" });
+ assert.deepEqual(reached[0].slice(0, 2), ["addAttachment", PLUGIN]);
+ assert.equal(reached[0][2].name, "a.txt");
+ assert.equal(reached[0][2].mimeType, "text/plain");
+ assert.deepEqual(bytesOf(0), [0x68, 0xc3, 0xa9], "a string is its UTF-8 bytes");
+
+ const whole = new Uint8Array([9, 1, 2, 3, 9]);
+ await add(whole.subarray(1, 4), "chart.png", "image/png");
+ assert.deepEqual(bytesOf(1), [1, 2, 3], "a view is only its own bytes");
+ const buffer = new Uint8Array([4, 5]).buffer;
+ await add(buffer, "b.bin", "application/octet-stream");
+ new Uint8Array(buffer)[0] = 0;
+ whole[1] = 0;
+ assert.deepEqual(bytesOf(2), [4, 5], "the host keeps a copy");
+ assert.deepEqual(bytesOf(1), [1, 2, 3]);
+
+ // Text that merely starts like a path is content once it runs over lines.
+ await add("/* reset */\nbody { margin: 0 }", "reset.css", "text/css");
+ await add("see https://example.com", "note.txt");
+
+ for (const reference of [
+ "/etc/passwd",
+ " /tmp/a.png\n",
+ "~/notes.txt",
+ "./a.txt",
+ "../a.txt",
+ "C:\\Users\\me\\a.txt",
+ "c:/a.txt",
+ "\\\\server\\share\\a.txt",
+ "file:///etc/passwd",
+ "FILE:/etc/passwd",
+ "https://example.com/a.png",
+ "http:example.com",
+ "data:text/plain,hi",
+ "blob:https://example.com/1",
+ "ftp://example.com/a",
+ "s3://bucket/key",
+ ]) {
+ await assert.rejects(
+ add(reference),
+ rejectsWith("PLUGIN_ATTACHMENT_REFERENCE_REFUSED"),
+ JSON.stringify(reference),
+ );
+ }
+ await assert.rejects(
+ add(new Uint8Array(16 * 1024 * 1024 + 1), "big.bin"),
+ rejectsWith("PLUGIN_ATTACHMENT_LIMIT"),
+ );
+ await add(new Uint8Array(16 * 1024 * 1024), "max.bin");
+ assert.equal(reached.length, 6);
+});
+
test("plugin.call relays the plugin's own id and the JSON reading of its args", async () => {
const { routes, calls } = fakeRoutes({ call: async (_id, method) => ({ answered: method }) });
const { dispatch } = createDispatchChannel(PLUGIN, ["plugin.call"], routes);
@@ -162,14 +366,13 @@ test("plugin.call passes the relay's coded refusal through untouched", async ()
test("closing the channel rejects the calls in flight and refuses every later dispatch", async () => {
const pending = [];
- const { routes } = fakeRoutes({
- call: () => {
- const answer = deferred();
- pending.push(answer);
- return answer.promise;
- },
- });
- const channel = createDispatchChannel(PLUGIN, BOTH, routes);
+ const later = () => {
+ const answer = deferred();
+ pending.push(answer);
+ return answer.promise;
+ };
+ const { routes } = fakeRoutes({ call: later, composer: { addAttachment: later } });
+ const channel = createDispatchChannel(PLUGIN, ALL, routes);
const settledFirst = channel.dispatch("plugin.call", { method: "first" });
pending[0].resolve("before the end");
@@ -177,42 +380,79 @@ test("closing the channel rejects the calls in flight and refuses every later di
const late = channel.dispatch("plugin.call", { method: "late" });
const failing = channel.dispatch("plugin.call", { method: "failing" });
+ const staging = channel.dispatch("attachments.add", {
+ name: "a.txt",
+ mimeType: "text/plain",
+ content: "hi",
+ });
channel.close();
await assert.rejects(late, rejectsWith("PLUGIN_UNLOADED"));
await assert.rejects(failing, rejectsWith("PLUGIN_UNLOADED"));
+ await assert.rejects(staging, rejectsWith("PLUGIN_UNLOADED"));
// The answers that arrive afterwards go nowhere.
pending[1].resolve("after the end");
pending[2].reject(new Error("after the end"));
+ pending[3].resolve({ id: "late" });
await assert.rejects(channel.dispatch("plugin.call", { method: "ping" }), rejectsWith("PLUGIN_UNLOADED"));
await assert.rejects(channel.dispatch("composer.insertText", { text: "hi" }), rejectsWith("PLUGIN_UNLOADED"));
await assert.rejects(channel.dispatch("ui.toast", {}), rejectsWith("PLUGIN_UNLOADED"));
channel.close();
- assert.equal(pending.length, 3, "nothing is relayed once the channel is closed");
+ assert.equal(pending.length, 4, "nothing is relayed once the channel is closed");
+});
+
+test("a user gesture is a trusted input event of the running handler", () => {
+ for (const type of ["click", "keydown", "pointerup", "input", "change", "submit"]) {
+ assert.equal(isUserGesture({ isTrusted: true, type }), true, type);
+ }
+ assert.equal(isUserGesture({ isTrusted: false, type: "click" }), false, "a synthetic click");
+ for (const type of ["load", "message", "focus", "scroll", "mousemove", "transitionend"]) {
+ assert.equal(isUserGesture({ isTrusted: true, type }), false, type);
+ }
+ assert.equal(isUserGesture(undefined), false, "outside any event");
});
-test("the default routes reach the composer insert bridge and the main-process relay", async (t) => {
+test("the default routes reach the draft bridge, the window's event and the main-process relay", async (t) => {
const originalWindow = globalThis.window;
t.after(() => {
- resetComposerInsertBridge();
globalThis.window = originalWindow;
});
- const { dispatch } = createDispatchChannel(PLUGIN, BOTH);
+ const { dispatch } = createDispatchChannel(PLUGIN, ALL);
- resetComposerInsertBridge();
await assert.rejects(
dispatch("composer.insertText", { text: "hi" }),
rejectsWith("PLUGIN_ACTION_NO_COMPOSER"),
);
- const inserted = [];
- registerComposerInsert((text) => inserted.push(text));
- assert.deepEqual(await dispatch("composer.insertText", { text: "hi" }), { ok: true });
- assert.deepEqual(inserted, ["hi"]);
- registerComposerInsert(null);
+ const writes = [];
+ let text = "";
+ const handle = {
+ read: () => ({ draftKey: "session:s1", sessionId: "s1", text, references: [] }),
+ focused: () => false,
+ selection: () => ({ start: text.length, end: text.length }),
+ write: (next, _references, caret, focus) => writes.push({ next, caret, focus }),
+ stage: async () => {
+ throw new Error("not staged in this test");
+ },
+ };
+ const unregister = composerDraftBridge.register(handle);
+ t.after(unregister);
+ const inserted = await dispatch("composer.insertText", { text: "hi" });
+ assert.equal(inserted.ok, true);
+ assert.deepEqual(writes, [{ next: "hi", caret: 2, focus: true }]);
+ text = "hi";
+ composerDraftBridge.publish(handle);
+
+ // No window event: the write is remote.
+ const { generation } = await dispatch("composer.readDraft", {});
await assert.rejects(
- dispatch("composer.insertText", { text: "again" }),
- rejectsWith("PLUGIN_ACTION_NO_COMPOSER"),
+ dispatch("composer.replaceDraft", { expectedGeneration: generation, text: "x" }),
+ rejectsWith("PLUGIN_DRAFT_REMOTE"),
);
+ globalThis.window = { event: { isTrusted: true, type: "click" } };
+ assert.equal((await dispatch("composer.replaceDraft", { expectedGeneration: generation, text: "x" })).ok, true);
+ assert.equal(writes.at(-1).next, "x");
+ unregister();
+ await assert.rejects(dispatch("composer.readDraft", {}), rejectsWith("PLUGIN_ACTION_NO_COMPOSER"));
const invoked = [];
let reply = { ok: true, data: { pong: true } };
diff --git a/apps/desktop/test/plugin-renderer-loader.test.mjs b/apps/desktop/test/plugin-renderer-loader.test.mjs
index c2177bb36..c3c3d6d07 100644
--- a/apps/desktop/test/plugin-renderer-loader.test.mjs
+++ b/apps/desktop/test/plugin-renderer-loader.test.mjs
@@ -9,9 +9,9 @@ register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
* one load per plugin generation, a frozen `pi` bound to the plugin, and an
* end that takes everything the load registered, injected or dispatched with
* it before the plugin's `onUnload` runs, whatever the plugin did. The
- * registry, the layer stack and the dispatch channel are the real ones; only
- * the module import, the style sheets, the document under the layers and the
- * routes behind the channel are faked.
+ * registry, the layer stack, the dispatch channel and the draft bridge are the
+ * real ones; only the module import, the style sheets, the document under the
+ * layers, the composer and the routes behind the channel are faked.
*/
const { RendererModuleLoader, rendererModuleUrl, rendererLoadSpecs } = await import(
"../src/plugins/renderer-host/loader.ts"
@@ -20,6 +20,9 @@ const { SlotRegistry } = await import("../src/plugins/renderer-slots/registry.ts
const { createDispatchChannel } = await import("../src/plugins/renderer-host/dispatch.ts");
const { PluginRendererError } = await import("../src/plugins/renderer-error.ts");
const { PluginLayerStack } = await import("../src/plugins/renderer-layers/layer-stack.ts");
+const { ComposerDraftBridge } = await import(
+ "../src/features/chat/composer/plugins/draft-bridge.ts"
+);
const PLUGIN = "demo.lab";
const component = () => null;
@@ -68,6 +71,7 @@ function harness(modules = {}) {
const imports = [];
const warnings = [];
const calls = [];
+ const drafts = new ComposerDraftBridge((message, error) => warnings.push({ message, error }));
let answerCall = () => Promise.resolve({ pong: true });
const loader = new RendererModuleLoader({
importModule: async (url) => {
@@ -92,8 +96,10 @@ function harness(modules = {}) {
calls.push({ id, method, args });
return answerCall(id, method, args);
},
- insertText: () => true,
+ composer: drafts,
+ userGesture: () => false,
}),
+ subscribeDraft: (pluginId, listener) => drafts.subscribe(pluginId, listener),
warn: (message, error) => warnings.push({ message, error }),
});
return {
@@ -105,6 +111,7 @@ function harness(modules = {}) {
imports,
warnings,
calls,
+ drafts,
openLayerFor: (pluginId) => layerStack.open(pluginId),
answerCallsWith(fn) {
answerCall = fn;
@@ -143,7 +150,10 @@ test("onLoad gets a frozen pi bound to its plugin, and what it registers shows u
assert.deepEqual(await h.loader.load(spec()), { status: "loaded" });
assert.deepEqual(h.imports, [url()]);
- assert.ok(Object.isFrozen(pi) && Object.isFrozen(pi.plugin) && Object.isFrozen(pi.slots) && Object.isFrozen(pi.ui));
+ assert.ok(
+ [pi, pi.plugin, pi.slots, pi.ui, pi.composer].every((part) => Object.isFrozen(part)),
+ );
+ assert.deepEqual(Object.keys(pi).sort(), ["composer", "dispatch", "plugin", "slots", "ui"]);
assert.deepEqual({ ...pi.plugin }, { id: PLUGIN, version: "1.2.3" });
assert.deepEqual(
h.registry.getSnapshot().entries.map((entry) => [entry.pluginId, entry.slot, entry.key]),
@@ -318,6 +328,54 @@ test("ending a load disposes its registrations, styles, layers and calls before
assert.equal(observed.length, 1, "unloading twice runs onUnload once");
});
+test("a draft subscription takes the readDraft declaration and ends with the load", async () => {
+ let pi;
+ const h = harness({
+ [url()]: {
+ onLoad(api) {
+ pi = api;
+ },
+ },
+ [url("demo.mute")]: {
+ onLoad(api) {
+ assert.throws(
+ () => api.composer.subscribeDraft(() => {}),
+ (error) => error instanceof PluginRendererError && error.code === "PLUGIN_ACTION_UNDECLARED",
+ );
+ },
+ },
+ });
+ await h.loader.load(spec(PLUGIN, { actions: ["composer.readDraft"] }));
+ assert.deepEqual(await h.loader.load(spec("demo.mute")), { status: "loaded" });
+ assert.throws(() => pi.composer.subscribeDraft("not a listener"), TypeError);
+
+ const seen = [];
+ const stop = pi.composer.subscribeDraft((snapshot) => seen.push(snapshot?.text ?? null));
+ pi.composer.subscribeDraft((snapshot) => seen.push(snapshot ? "second" : "second: none"));
+ let text = "hello";
+ const handle = {
+ read: () => ({ draftKey: "session:s1", sessionId: "s1", text, references: [] }),
+ focused: () => false,
+ selection: () => ({ start: text.length, end: text.length }),
+ write: () => {},
+ stage: async () => {
+ throw new Error("not staged in this test");
+ },
+ };
+ h.drafts.register(handle);
+ stop();
+ text = "hello!";
+ h.drafts.publish(handle);
+ assert.deepEqual(seen, [null, "second: none", "hello", "second", "second"]);
+
+ await h.loader.unload(PLUGIN);
+ text = "after the end";
+ h.drafts.publish(handle);
+ assert.equal(seen.length, 5, "the end of the load ends its subscriptions");
+ assert.throws(() => pi.composer.subscribeDraft(() => {}), unloadedError);
+ assert.deepEqual(h.warnings, []);
+});
+
test("a registration or layer the plugin disposed itself is not disposed again at the end", async () => {
let dispose;
let layer;
diff --git a/apps/desktop/test/plugin-slot-registry.test.mjs b/apps/desktop/test/plugin-slot-registry.test.mjs
index 35689d16d..513a95296 100644
--- a/apps/desktop/test/plugin-slot-registry.test.mjs
+++ b/apps/desktop/test/plugin-slot-registry.test.mjs
@@ -86,6 +86,7 @@ test("every accepted registration and disposal publishes a new snapshot; a refus
const empty = registry.getSnapshot();
assert.equal(empty.version, 0);
assert.deepEqual(empty.entries, []);
+ assert.deepEqual(empty.triggers, []);
const dispose = registry.register(PLUGIN, { slot: "entryExtra", component }, []);
const registered = registry.getSnapshot();
@@ -161,6 +162,12 @@ test("malformed registrations are refused with their code and change nothing", (
["a bare language", { slot: "blockRenderer", component, language: "chart" }, "PLUGIN_SLOT_INVALID_KEY"],
["an empty suffix", { slot: "blockRenderer", component, language: "demo.lab:" }, "PLUGIN_SLOT_INVALID_KEY"],
["a suffix with a space", { slot: "blockRenderer", component, language: "demo.lab:bar chart" }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["a trigger without items", { slot: "composerTrigger", trigger: "#" }, "PLUGIN_SLOT_INVALID_COMPONENT"],
+ ["a trigger with a component", { slot: "composerTrigger", trigger: "#", component }, "PLUGIN_SLOT_INVALID_COMPONENT"],
+ ["a trigger with positions", { slot: "composerTrigger", trigger: "#", items: () => [], positions: ["left"] }, "PLUGIN_SLOT_INVALID_POSITION"],
+ ["a trigger without a symbol", { slot: "composerTrigger", items: () => [] }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["a trigger of another symbol", { slot: "composerTrigger", trigger: "$", items: () => [] }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["a trigger of two symbols", { slot: "composerTrigger", trigger: "##", items: () => [] }, "PLUGIN_SLOT_INVALID_KEY"],
];
const registry = new SlotRegistry();
for (const [label, registration, code] of cases) {
@@ -172,6 +179,7 @@ test("malformed registrations are refused with their code and change nothing", (
}
assert.equal(registry.getSnapshot().version, 0);
assert.deepEqual(registry.getSnapshot().entries, []);
+ assert.deepEqual(registry.getSnapshot().triggers, []);
});
test("a tool card is keyed by the plugin's qualified tool name, first claim wins", () => {
@@ -232,3 +240,45 @@ test("a block renderer is keyed by its normalized language tag, first claim wins
// Keys are per slot: the same string never matches another slot's entry.
assert.equal(registry.entryForKey("toolCard", "demo.lab:chart"), undefined);
});
+
+test("a composer trigger is keyed by its symbol, full-width folded, first claim wins", () => {
+ const registry = new SlotRegistry();
+ const items = () => [];
+ let notified = 0;
+ registry.subscribe(() => {
+ notified += 1;
+ });
+ const disposeHash = registry.register(PLUGIN, { slot: "composerTrigger", trigger: "\uFF03", items }, []);
+ assert.equal(notified, 1);
+ const hash = registry.triggerFor("#");
+ assert.equal(hash?.pluginId, PLUGIN);
+ assert.equal(hash?.trigger, "#");
+ assert.equal(hash?.items, items);
+ assert.equal("component" in hash, false, "a trigger registers no component");
+ assert.deepEqual(registry.getSnapshot().entries, [], "triggers never reach component outlets");
+
+ // One plugin per symbol, the same plugin included, whichever form it names.
+ for (const [pluginId, trigger] of [[OTHER, "#"], [PLUGIN, "#"], [OTHER, "\uFF03"]]) {
+ assert.throws(
+ () => registry.register(pluginId, { slot: "composerTrigger", trigger, items }, []),
+ refusedWith("PLUGIN_SLOT_DUPLICATE"),
+ `${pluginId} ${trigger}`,
+ );
+ }
+ assert.equal(notified, 1, "a refused claim publishes nothing");
+
+ registry.register(OTHER, { slot: "composerTrigger", trigger: "@", items }, []);
+ registry.register(PLUGIN, { slot: "composerTrigger", trigger: "/", items }, []);
+ assert.deepEqual(
+ registry.getSnapshot().triggers.map((entry) => [entry.trigger, entry.pluginId]),
+ [["#", PLUGIN], ["@", OTHER], ["/", PLUGIN]],
+ );
+
+ // The symbol frees up with its disposer, once.
+ disposeHash();
+ disposeHash();
+ assert.equal(registry.triggerFor("#"), undefined);
+ assert.equal(registry.getSnapshot().triggers.length, 2);
+ registry.register(OTHER, { slot: "composerTrigger", trigger: "#", items }, []);
+ assert.equal(registry.triggerFor("#")?.pluginId, OTHER);
+});
diff --git a/apps/desktop/test/plugin-ui-slots-lab.test.mjs b/apps/desktop/test/plugin-ui-slots-lab.test.mjs
index dce55ee37..62d5599ed 100644
--- a/apps/desktop/test/plugin-ui-slots-lab.test.mjs
+++ b/apps/desktop/test/plugin-ui-slots-lab.test.mjs
@@ -72,8 +72,9 @@ function refusedWith(code) {
/**
* The lab's renderer entry, loaded by the production loader from the files
* the runtime serves for its current generation, into the registry the host
- * outlets read. Its `plugin.call` goes to the runtime; its composer inserts
- * are recorded.
+ * outlets read. Its `plugin.call` goes to the runtime; its composer words go
+ * to a real draft bridge over a fake composer, whose writes are recorded and
+ * whose staged files are kept in memory. `gesture.on` stands for a click.
*/
async function labWindow(t) {
const runtime = await labRuntime(t);
@@ -81,11 +82,15 @@ async function labWindow(t) {
const { RendererModuleLoader, rendererModuleUrl } = await ssr.load("/src/plugins/renderer-host/loader.ts");
const { createDispatchChannel } = await ssr.load("/src/plugins/renderer-host/dispatch.ts");
const { PluginLayerStack } = await ssr.load("/src/plugins/renderer-layers/layer-stack.ts");
+ const { ComposerDraftBridge } = await ssr.load("/src/features/chat/composer/plugins/draft-bridge.ts");
const layerDocument = fakeLayerDocument();
const layers = new PluginLayerStack(() => layerDocument);
const descriptor = runtime.rendererDescriptor(LAB);
const sheets = new Set();
- const inserted = [];
+ const composer = fakeComposer();
+ const drafts = new ComposerDraftBridge((message, error) => assert.fail(`${message}: ${error?.stack ?? error}`));
+ drafts.register(composer.handle);
+ const gesture = { on: false };
const channels = [];
const loader = new RendererModuleLoader({
importModule: (url) => {
@@ -102,16 +107,48 @@ async function labWindow(t) {
openChannel: (pluginId, actions) => {
const channel = createDispatchChannel(pluginId, actions, {
pluginCall: (id, method, args) => runtime.callRenderer(id, method, args),
- insertText: (text) => inserted.push(text) > 0,
+ composer: drafts,
+ userGesture: () => gesture.on,
});
channels.push(channel);
return channel;
},
+ subscribeDraft: (pluginId, listener) => drafts.subscribe(pluginId, listener),
warn: (message, error) => assert.fail(`${message}: ${error?.stack ?? error}`),
});
const outcome = await loader.load({ pluginId: LAB, version: manifest.version, descriptor });
t.after(() => loader.unload(LAB));
- return { ...ssr, runtime, loader, outcome, sheets, inserted, dispatch: channels[0].dispatch };
+ return { ...ssr, runtime, loader, outcome, sheets, composer, drafts, gesture, dispatch: channels[0].dispatch };
+}
+
+/** A composer on `SESSION`'s draft that renders a write when told to. */
+function fakeComposer() {
+ const state = { text: "", references: [], writes: [], staged: [] };
+ const handle = {
+ read: () => ({ draftKey: `session:${SESSION}`, sessionId: SESSION, text: state.text, references: state.references }),
+ focused: () => false,
+ selection: () => ({ start: state.text.length, end: state.text.length }),
+ write: (text, references, caret, focus) => state.writes.push({ text, references, caret, focus }),
+ stage: async (sessionId, file) => {
+ state.staged.push({ sessionId, file });
+ return {
+ path: `/scratch/${sessionId}/${file.name}`,
+ name: file.name,
+ kind: file.mimeType.startsWith("image/") ? "image" : "file",
+ mimeType: file.mimeType,
+ size: file.data.byteLength,
+ };
+ },
+ };
+ return { state, handle };
+}
+
+/** The composer renders its last write and tells the bridge. */
+function render(lab) {
+ const last = lab.composer.state.writes.at(-1);
+ lab.composer.state.text = last.text;
+ lab.composer.state.references = last.references;
+ lab.drafts.publish(lab.composer.handle);
}
const USER = { id: "u1", role: "user", content: "Probe the lab\nplease", status: "complete", createdAt: "2026-09-24T00:00:00.000Z" };
@@ -225,13 +262,17 @@ test("the renderer entry loads a sample into every slot", async (t) => {
assert.equal([...reply.matchAll(/class="lab-bar-row"/g)].length, 2, "one bar per data line");
assert.match(reply, /data-lab-message="a2"/, "the entryExtra panel sits under the final reply");
- // The layer launcher opens its layers on a click, never on its own.
+ // The layer launcher and the draft lab open their layers on a click, never
+ // on their own.
assert.deepEqual(samples(toolbar()), [
"composerControl:left",
+ "composerControl:draft",
"composerControl:right",
"composerControl:crash",
"composerControl:layers",
]);
+ assert.match(toolbar(), /data-lab-draft="none"><\/span>/, "no draft before the first effect");
+ assert.equal(lab.registry.triggerFor("#")?.pluginId, LAB, "the lab owns #");
});
test("the samples' calls work through the host channel", async (t) => {
@@ -241,8 +282,99 @@ test("the samples' calls work through the host channel", async (t) => {
echo: { messageId: "a2" },
});
await assert.rejects(lab.dispatch("plugin.call", { method: "lab.refuse" }), refusedWith("LAB_REFUSED"));
- assert.deepEqual(await lab.dispatch("composer.insertText", { text: "lab: hi " }), { ok: true });
- assert.deepEqual(lab.inserted, ["lab: hi "]);
+ assert.equal((await lab.dispatch("composer.insertText", { text: "lab: hi " })).ok, true);
+ assert.deepEqual(
+ lab.composer.state.writes.map(({ text, focus }) => ({ text, focus })),
+ [{ text: "lab: hi ", focus: true }],
+ );
+});
+
+test("the # trigger lists the lab's issues, and fails or overflows on request", async (t) => {
+ const lab = await labWindow(t);
+ const { askPluginTrigger } = await lab.load("/src/features/chat/composer/plugins/plugin-triggers.ts");
+ const { items } = lab.registry.triggerFor("#");
+ const ask = (query) => askPluginTrigger(items, { trigger: "#", query }, LAB);
+
+ assert.deepEqual(await ask("caret"), [
+ { label: "#7", send: "Lab issue #7: Composer loses the caret after a paste", detail: "Composer loses the caret after a paste" },
+ ]);
+ assert.equal((await ask("")).length, 3);
+ assert.equal((await ask("many")).length, 50, "the host keeps its first 50 rows");
+ const warn = t.mock.method(console, "warn", () => {});
+ assert.equal(await ask("fail"), null, "a throw collapses the lab's group");
+ assert.equal(warn.mock.callCount(), 1);
+});
+
+test("Polish rewrites the draft around its chips, only from a click", async (t) => {
+ const lab = await labWindow(t);
+ const { createFileReference, nextChipToken } = await lab.load("/src/features/chat/composer/editor.ts");
+ const { polished } = await import(pathToFileURL(join(LAB_DIR, "renderer/composer.mjs")).href);
+ const chip = createFileReference("/w/a.ts", "a.ts", SESSION, { kind: "file", token: nextChipToken() });
+ lab.composer.state.text = ` fix ${chip.token} now `;
+ lab.composer.state.references = [chip];
+ lab.drafts.publish(lab.composer.handle);
+
+ const snapshot = await lab.dispatch("composer.readDraft", {});
+ await assert.rejects(lab.dispatch("composer.replaceDraft", polished(snapshot)), refusedWith("PLUGIN_DRAFT_REMOTE"));
+ lab.gesture.on = true;
+ const written = await lab.dispatch("composer.replaceDraft", polished(snapshot));
+ const write = lab.composer.state.writes.at(-1);
+ const stamp = write.references.at(-1);
+ assert.equal(write.text, `Fix ${chip.token} now ${stamp.token}`);
+ assert.equal(write.focus, false);
+ assert.deepEqual(stamp.plugin, { kind: "mark", pluginId: LAB, send: "(tidied by the UI Slots Lab)" });
+ render(lab);
+
+ // Polishing again replaces the stamp instead of adding one.
+ const again = await lab.dispatch("composer.readDraft", {});
+ assert.equal(again.generation, written.generation);
+ await lab.dispatch("composer.replaceDraft", polished(again));
+ render(lab);
+ const after = await lab.dispatch("composer.readDraft", {});
+ assert.equal(after.text, "Fix \uFFFC now \uFFFC");
+ assert.deepEqual(
+ after.marks.map((mark) => [mark.kind, mark.label]),
+ [
+ ["host", "a.ts"],
+ ["plugin", "lab \u2713"],
+ ],
+ );
+ await assert.rejects(lab.dispatch("composer.replaceDraft", polished(snapshot)), refusedWith("PLUGIN_DRAFT_STALE"));
+});
+
+test("the attachment controls stage the lab's files into the session's draft", async (t) => {
+ const lab = await labWindow(t);
+ const note = await lab.dispatch("attachments.add", {
+ name: "lab-note.md",
+ mimeType: "text/markdown",
+ content: "# Lab note\n",
+ });
+ render(lab);
+ await lab.dispatch("attachments.add", { name: "lab-dot.png", mimeType: "image/png", content: new Uint8Array([137, 80]) });
+ render(lab);
+ assert.deepEqual(
+ lab.composer.state.staged.map(({ sessionId, file }) => [sessionId, file.name, file.data.byteLength]),
+ [
+ [SESSION, "lab-note.md", 11],
+ [SESSION, "lab-dot.png", 2],
+ ],
+ );
+ assert.deepEqual(
+ (await lab.dispatch("attachments.list", {})).map(({ name, mimeType, size }) => [name, mimeType, size]),
+ [
+ ["lab-note.md", "text/markdown", 11],
+ ["lab-dot.png", "image/png", 2],
+ ],
+ );
+ assert.equal((await lab.dispatch("composer.readDraft", {})).text, "\uFFFC", "only the note is a chip");
+ await assert.rejects(
+ lab.dispatch("attachments.add", { name: "passwd.txt", mimeType: "text/plain", content: "/etc/passwd" }),
+ refusedWith("PLUGIN_ATTACHMENT_REFERENCE_REFUSED"),
+ );
+ assert.deepEqual(await lab.dispatch("attachments.remove", { id: note.id }), { ok: true });
+ render(lab);
+ assert.equal(lab.composer.state.text, "");
+ await assert.rejects(lab.dispatch("attachments.remove", { id: "none" }), refusedWith("PLUGIN_ATTACHMENT_NOT_FOUND"));
});
test("unloading the renderer entry takes every sample and its styles with it", async (t) => {
@@ -252,6 +384,7 @@ test("unloading the renderer entry takes every sample and its styles with it", a
await lab.loader.unload(LAB);
assert.equal(lab.sheets.size, 0);
+ assert.equal(lab.registry.triggerFor("#"), undefined);
for (const html of [row(), turn(), toolbar()]) {
assert.deepEqual(samples(html), []);
assert.deepEqual(slotMounts(html), []);
diff --git a/examples/plugins/ui-slots-lab/manifest.json b/examples/plugins/ui-slots-lab/manifest.json
index 69c16f78e..0d49619d8 100644
--- a/examples/plugins/ui-slots-lab/manifest.json
+++ b/examples/plugins/ui-slots-lab/manifest.json
@@ -3,11 +3,19 @@
"id": "lab.ui-slots",
"name": "UI Slots Lab",
"version": "0.1.0",
- "description": "Test plugin with one visible sample in every renderer UI slot, plus controls that exercise dispatch, errors, crash isolation, the host size clamps and self-drawn layers",
+ "description": "Test plugin with one visible sample in every renderer UI slot, plus controls that exercise dispatch, errors, crash isolation, the host size clamps, self-drawn layers, the # trigger, the draft and attachments",
"author": "PI-Desktop",
"main": "main.js",
"renderer": "renderer/index.mjs",
- "rendererActions": ["plugin.call", "composer.insertText"],
+ "rendererActions": [
+ "plugin.call",
+ "composer.insertText",
+ "composer.readDraft",
+ "composer.replaceDraft",
+ "attachments.add",
+ "attachments.list",
+ "attachments.remove"
+ ],
"rendererCallMethods": ["lab.echo", "lab.refuse", "lab.stall"],
"contributes": {
"agentTools": [
diff --git a/examples/plugins/ui-slots-lab/renderer/composer.mjs b/examples/plugins/ui-slots-lab/renderer/composer.mjs
index ee890e85c..6c440124f 100644
--- a/examples/plugins/ui-slots-lab/renderer/composer.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/composer.mjs
@@ -1,9 +1,15 @@
/**
- * Composer samples: a `composerControl` on each side of the toolbar and a
- * right-side control that crashes when asked.
+ * Composer samples: controls on each side of the toolbar, the `#` trigger,
+ * a draft lab panel where the draft is rewritten and attachments are added,
+ * and a right-side control that crashes when asked.
*/
-import { createElement as h } from "react";
-import { Button, Outcome, useCrash, useDispatch } from "./lab.mjs";
+import { createElement as h, useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { Button, Outcome, subscribeDraft, useCrash, useDispatch } from "./lab.mjs";
+import { useLayer } from "./layers.mjs";
+
+/** Where a mark sits in a draft snapshot's text. */
+const MARK = "\uFFFC";
/** Left: insert text at the caret. Right: a `plugin.call` round trip. */
export function ComposerControl({ position }) {
@@ -12,16 +18,16 @@ export function ComposerControl({ position }) {
return h("span", { className: "lab-action", "data-lab": "composerControl:left" },
h(Button, {
lab: "insert",
- onClick: () => run("composer.insertText", { text: "lab: hello from the composer " }, () => "inserted"),
- }, "Lab insert"),
+ onClick: () => run("composer.insertText", { text: "lab: hello from the composer " }, () => "✓"),
+ }, "Insert"),
h(Outcome, { outcome }));
}
return h("span", { className: "lab-action", "data-lab": "composerControl:right" },
h(Button, {
lab: "echo",
onClick: () => run("plugin.call", { method: "lab.echo", args: { from: "composer" } }, (answer) =>
- answer?.echo?.from === "composer" ? "echo ✓" : "echo ✗"),
- }, "Lab echo"),
+ answer?.echo?.from === "composer" ? "✓" : "✗"),
+ }, "Echo"),
h(Outcome, { outcome }));
}
@@ -30,3 +36,181 @@ export function ComposerCrash() {
return h("span", { className: "lab-action", "data-lab": "composerControl:crash" },
h(Button, { lab: "crash", onClick: crash }, "Crash"));
}
+
+const ISSUES = [
+ { n: 7, title: "Composer loses the caret after a paste" },
+ { n: 12, title: "Chart block ignores empty lines" },
+ { n: 19, title: "Tool card flickers while running" },
+];
+
+/**
+ * The `#` trigger's list: the lab's issues matching the query. `#fail`
+ * throws, `#slow` answers past the host's budget and `#many` answers with
+ * more rows than the host keeps, so each collapse and cut shows on demand.
+ */
+export async function issueItems({ query }) {
+ if (query === "fail") throw new Error("lab: the # list failed on request");
+ if (query === "slow") await new Promise((resolve) => setTimeout(resolve, 3_000));
+ if (query === "many") {
+ return Array.from({ length: 60 }, (_, i) => ({ label: `#${i + 1}`, send: `Lab issue #${i + 1}` }));
+ }
+ const needle = query.toLowerCase();
+ return ISSUES.filter((issue) => `${issue.n} ${issue.title}`.toLowerCase().includes(needle)).map((issue) => ({
+ label: `#${issue.n}`,
+ send: `Lab issue #${issue.n}: ${issue.title}`,
+ detail: issue.title,
+ }));
+}
+
+/** The mark "Polish" leaves at the end of the draft; one at a time. */
+const STAMP = { label: "lab ✓", send: "(tidied by the UI Slots Lab)" };
+
+/**
+ * `snapshot` tidied into a `composer.replaceDraft` payload: every mark kept
+ * in place by id but the previous stamp, runs of spaces folded, the first
+ * letter capitalized, and a fresh stamp at the end.
+ */
+export function polished(snapshot) {
+ let at = 0;
+ const marks = [];
+ const kept = snapshot.text.replace(new RegExp(MARK, "g"), () => {
+ const mark = snapshot.marks[at++];
+ // Only the lab's own marks carry `send`, so this finds no one else's.
+ if (mark.kind === "plugin" && mark.send === STAMP.send) return "";
+ marks.push({ id: mark.id });
+ return MARK;
+ });
+ const tidy = kept.replace(/[ \t]+/g, " ").replace(/ *\n */g, "\n").trim();
+ const text = tidy.charAt(0).toUpperCase() + tidy.slice(1);
+ return {
+ expectedGeneration: snapshot.generation,
+ text: text ? `${text} ${MARK}` : MARK,
+ marks: [...marks, STAMP],
+ };
+}
+
+/**
+ * Left: a toggle for the draft lab that shows the generation it follows. The
+ * lab is a panel in its own layer docked above the composer, so the toolbar
+ * keeps one button's width however many controls the panel holds.
+ */
+export function ComposerDraft() {
+ const [draft, setDraft] = useState(null);
+ const [open, setOpen] = useState(false);
+ useEffect(() => subscribeDraft(setDraft), []);
+ return h("span", { className: "lab-action", "data-lab": "composerControl:draft" },
+ h(Button, { lab: "draft-panel", onClick: () => setOpen((now) => !now) },
+ "Draft",
+ h("span", { className: "lab-count", "data-lab-draft": draft ? String(draft.generation) : "none" },
+ draft ? ` g${draft.generation}` : "")),
+ open ? h(DraftPanel, { draft, onClose: () => setOpen(false) }) : null);
+}
+
+/**
+ * The draft lab: the followed draft read on demand and rewritten, and the
+ * lab's attachments. Clicking in it takes focus from the composer, which a
+ * rewrite needs; it closes only by its ✕ or the toggle.
+ */
+function DraftPanel({ draft, onClose }) {
+ const element = useLayer();
+ if (!element) return null;
+ return createPortal(
+ h("div", { className: "p-overlay p-overlay__corner lab-dock", "data-lab": "layer:composer" },
+ h("div", { className: "p-dialog", role: "dialog", "aria-label": "Lab draft" },
+ h("div", { className: "p-dialog-head" },
+ h("span", null, "Lab draft"),
+ h("button", {
+ type: "button",
+ className: "p-notice__dismiss",
+ "aria-label": "Close",
+ "data-lab-button": "draft-close",
+ onClick: onClose,
+ }, "✕")),
+ h("div", { className: "p-dialog__body lab-panel" },
+ h(DraftActions, { draft }),
+ h(AttachActions)))),
+ element,
+ );
+}
+
+/**
+ * A rewrite has to start in the click, so "Polish" uses the draft the
+ * subscription already holds; "Polish later" starts outside the click and
+ * is refused as remote.
+ */
+function DraftActions({ draft }) {
+ const [outcome, run] = useDispatch();
+ const summary = draft
+ ? `g${draft.generation} · ${draft.text.length} ch · ${draft.marks.length} marks`
+ : "no draft";
+ return h("div", { className: "lab-row", "data-lab": "layer:draft" },
+ h("span", { className: "lab-pill" }, summary),
+ h(Button, {
+ lab: "draft-read",
+ onClick: () => run("composer.readDraft", {}, (snapshot) => `read g${snapshot.generation}`),
+ }, "Read"),
+ h(Button, {
+ lab: "draft-polish",
+ onClick: () => {
+ if (draft) run("composer.replaceDraft", polished(draft), (result) => `polished g${result.generation}`);
+ },
+ }, "Polish"),
+ h(Button, {
+ lab: "draft-polish-late",
+ onClick: () => {
+ if (draft) setTimeout(() => run("composer.replaceDraft", polished(draft)), 0);
+ },
+ }, "Polish later"),
+ h(Outcome, { outcome }));
+}
+
+const NOTE = "# Lab note\n\nAttached by the UI Slots Lab through `attachments.add`.\n";
+const DOT_PNG =
+ "iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAIUlEQVR42mOwbvoGQV/ncUMQpggD9RThkYOLUFHRsPYdACyF7slzscLiAAAAAElFTkSuQmCC";
+
+function dotPng() {
+ return Uint8Array.from(atob(DOT_PNG), (char) => char.charCodeAt(0));
+}
+
+/**
+ * Attachments of the lab's own. A note is a chip in the text, an image
+ * joins the draft's images, a path is refused, and "Remove" takes back the
+ * last one this panel added.
+ */
+function AttachActions() {
+ const [outcome, run] = useDispatch();
+ const [ids, setIds] = useState([]);
+ const added = (what) => (answer) => {
+ setIds((current) => [...current, answer.id]);
+ return `${what} attached`;
+ };
+ return h("div", { className: "lab-row", "data-lab": "layer:attach" },
+ h(Button, {
+ lab: "attach-note",
+ onClick: () =>
+ run("attachments.add", { name: "lab-note.md", mimeType: "text/markdown", content: NOTE }, added("note")),
+ }, "Note"),
+ h(Button, {
+ lab: "attach-image",
+ onClick: () =>
+ run("attachments.add", { name: "lab-dot.png", mimeType: "image/png", content: dotPng() }, added("image")),
+ }, "Image"),
+ h(Button, {
+ lab: "attach-path",
+ onClick: () => run("attachments.add", { name: "passwd.txt", mimeType: "text/plain", content: "/etc/passwd" }),
+ }, "Path"),
+ h(Button, {
+ lab: "attach-list",
+ onClick: () =>
+ run("attachments.list", {}, (list) => `${list.length}: ${list.map((item) => item.name).join(", ")}`),
+ }, "List"),
+ h(Button, {
+ lab: "attach-remove",
+ onClick: () => {
+ const id = ids.at(-1) ?? "none";
+ setIds((current) => current.slice(0, -1));
+ run("attachments.remove", { id }, () => "removed");
+ },
+ }, "Remove"),
+ h(Outcome, { outcome }));
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/index.mjs b/examples/plugins/ui-slots-lab/renderer/index.mjs
index 81ac4c5f4..545a25c22 100644
--- a/examples/plugins/ui-slots-lab/renderer/index.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/index.mjs
@@ -4,13 +4,14 @@
* One visible sample in every renderer slot, each able to exercise the parts
* of the contract a person or the Electron E2E has to see working: dispatch
* round trips and their error codes, a crash the host contains, the host's
- * size clamps, and self-drawn layers over the app. A plain ES module with
+ * size clamps, self-drawn layers over the app, the `#` trigger, and the
+ * draft and attachment words. A plain ES module with
* no build step; `react` and `react-dom` resolve to the host's through the
* window's import map.
*/
import { bindLab } from "./lab.mjs";
import { ChartBlock, ProbeCard } from "./blocks.mjs";
-import { ComposerControl, ComposerCrash } from "./composer.mjs";
+import { ComposerControl, ComposerCrash, ComposerDraft, issueItems } from "./composer.mjs";
import { LayerLauncher } from "./layers.mjs";
import {
AssistantAction,
@@ -41,6 +42,8 @@ export function onLoad(pi) {
pi.slots.register({ slot: "blockRenderer", language: `${pi.plugin.id}:chart`, component: ChartBlock });
pi.slots.register({ slot: "composerControl", component: ComposerControl });
+ pi.slots.register({ slot: "composerControl", component: ComposerDraft, positions: ["left"] });
pi.slots.register({ slot: "composerControl", component: ComposerCrash, positions: ["right"] });
pi.slots.register({ slot: "composerControl", component: LayerLauncher, positions: ["right"] });
+ pi.slots.register({ slot: "composerTrigger", trigger: "#", items: issueItems });
}
diff --git a/examples/plugins/ui-slots-lab/renderer/lab.mjs b/examples/plugins/ui-slots-lab/renderer/lab.mjs
index 3b61674ce..a56438e6d 100644
--- a/examples/plugins/ui-slots-lab/renderer/lab.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/lab.mjs
@@ -15,6 +15,14 @@ export function bindLab(pi) {
labPi = pi;
}
+/**
+ * Follow the composer draft (`pi.composer.subscribeDraft`); the returned
+ * call stops following it.
+ */
+export function subscribeDraft(listener) {
+ return labPi.composer.subscribeDraft(listener);
+}
+
/** A layer above the app for a self-drawn dialog (`pi.ui.openLayer`). */
export function openLayer() {
return labPi.ui.openLayer();
diff --git a/examples/plugins/ui-slots-lab/renderer/layers.mjs b/examples/plugins/ui-slots-lab/renderer/layers.mjs
index 9865e45d8..1432b7547 100644
--- a/examples/plugins/ui-slots-lab/renderer/layers.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/layers.mjs
@@ -10,7 +10,7 @@ import { createPortal } from "react-dom";
import { Button, openLayer } from "./lab.mjs";
/** The element of a layer held open while the caller is mounted. */
-function useLayer() {
+export function useLayer() {
const [layer, setLayer] = useState(null);
useEffect(() => {
const opened = openLayer();
@@ -73,7 +73,7 @@ export function LayerLauncher() {
const [wizard, setWizard] = useState(false);
const [notice, setNotice] = useState(false);
return h("span", { className: "lab-action", "data-lab": "composerControl:layers" },
- h(Button, { lab: "wizard", onClick: () => setWizard(true) }, "Lab wizard"),
+ h(Button, { lab: "wizard", onClick: () => setWizard(true) }, "Wizard"),
wizard ? h(Wizard, { onClose: () => setWizard(false), onNotice: () => setNotice(true) }) : null,
notice ? h(Notice, { onClose: () => setNotice(false) }) : null);
}
diff --git a/examples/plugins/ui-slots-lab/renderer/styles.mjs b/examples/plugins/ui-slots-lab/renderer/styles.mjs
index abdbf93ea..ab06531eb 100644
--- a/examples/plugins/ui-slots-lab/renderer/styles.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/styles.mjs
@@ -31,6 +31,7 @@ export const LAB_CSS = `
}
.lab-btn {
padding: 1px 8px;
+ white-space: nowrap;
border: 1px solid var(--ds-border-default);
border-radius: 6px;
background: transparent;
@@ -42,7 +43,12 @@ export const LAB_CSS = `
.lab-btn:hover {
background: var(--ds-bg-hover);
}
+.lab-count {
+ color: var(--ds-text-secondary);
+ font-size: 10px;
+}
.lab-result {
+ white-space: nowrap;
color: var(--ds-text-muted);
font-size: 11px;
}
@@ -54,11 +60,21 @@ export const LAB_CSS = `
}
.lab-session, .lab-pill {
padding: 0 6px;
+ white-space: nowrap;
border-radius: 99px;
background: var(--ds-bg-chip);
color: var(--ds-text-secondary);
font-size: 10px;
}
+.lab-dock {
+ padding-bottom: 180px;
+}
+.lab-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ font-size: 12px;
+}
.lab-running { color: var(--ds-warning); }
.lab-success { color: var(--ds-success); }
.lab-error, .lab-pill.lab-error { color: var(--ds-error); }
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 87009a180..bc9a3eedf 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -266,6 +266,8 @@ export const de = {
"sessionTranscriptEmpty": "Der Verlauf dieser Sitzung konnte nicht gelesen werden. Bitte die Sitzung erneut öffnen.",
"fileMenu": "Dateiverweise",
"removeFileReference": "Dateiverweis {{name}} entfernen",
+ "removePluginMark": "{{name}} entfernen",
+ "pluginTriggerMenu": "Plugin-Vorschläge",
"messageAttachments": "Anhänge in dieser Nachricht",
"fileEmpty": "Keine übereinstimmenden Dateien",
"fileNoWorkspace": "Öffnen Sie ein Projekt, um auf Dateien zu verweisen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index b9e7f6892..5af051f86 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -273,6 +273,8 @@ export const en = {
sessionTranscriptEmpty: "This session's history could not be read. Reopen the session to try again.",
fileMenu: "File references",
removeFileReference: "Remove file reference {{name}}",
+ removePluginMark: "Remove {{name}}",
+ pluginTriggerMenu: "Plugin suggestions",
messageAttachments: "Attachments in this message",
fileEmpty: "No matching files",
fileNoWorkspace: "Open a project to reference files",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index a2c06e034..152f2e68c 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -266,6 +266,8 @@ export const es = {
"sessionTranscriptEmpty": "No se pudo leer el historial de esta sesión. Vuelve a abrirla para intentarlo de nuevo.",
"fileMenu": "Referencias de archivos",
"removeFileReference": "Eliminar referencia de archivo {{name}}",
+ "removePluginMark": "Eliminar {{name}}",
+ "pluginTriggerMenu": "Sugerencias de plugins",
"messageAttachments": "Archivos adjuntos en este mensaje",
"fileEmpty": "No hay archivos coincidentes",
"fileNoWorkspace": "Abrir un proyecto para hacer referencia a archivos",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 29e9b73f3..6d748c3aa 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -266,6 +266,8 @@ export const fr = {
"sessionTranscriptEmpty": "L'historique de cette session n'a pas pu être lu. Rouvrez la session pour réessayer.",
"fileMenu": "Références de fichiers",
"removeFileReference": "Supprimer la référence de fichier {{name}}",
+ "removePluginMark": "Supprimer {{name}}",
+ "pluginTriggerMenu": "Suggestions de plugins",
"messageAttachments": "Pièces jointes à ce message",
"fileEmpty": "Aucun fichier correspondant",
"fileNoWorkspace": "Ouvrir un projet pour référencer les fichiers",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index b02215a83..07c444edd 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -275,6 +275,8 @@ export const ko = {
sessionTranscriptEmpty: "이 세션의 기록을 읽지 못했습니다. 세션을 다시 열어 시도하세요.",
fileMenu: "파일 참조",
removeFileReference: "파일 참조 {{name}} 제거",
+ removePluginMark: "{{name}} 제거",
+ pluginTriggerMenu: "플러그인 제안",
messageAttachments: "이 메시지의 첨부 파일",
fileEmpty: "일치하는 파일 없음",
fileNoWorkspace: "파일을 참조하려면 프로젝트를 여세요",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 452502bb8..2b2d6f9a9 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -265,6 +265,8 @@ export const ptBR = {
sessionTranscriptEmpty: "Não foi possível ler o histórico desta sessão. Reabra-a para tentar novamente.",
fileMenu: "Referências a arquivos",
removeFileReference: "Remover referência de arquivo {{name}}",
+ removePluginMark: "Remover {{name}}",
+ pluginTriggerMenu: "Sugestões de plugins",
messageAttachments: "Anexos desta mensagem",
fileEmpty: "Nenhum arquivo correspondente",
fileNoWorkspace: "Abra um projeto para referenciar arquivos",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index c3c7364bf..59b87fbe2 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -275,6 +275,8 @@ export const tr = {
sessionTranscriptEmpty: "Bu oturumun geçmişi okunamadı. Yeniden denemek için oturumu tekrar açın.",
fileMenu: "Dosya başvuruları",
removeFileReference: "{{name}} dosya başvurusunu kaldır",
+ removePluginMark: "{{name}} öğesini kaldır",
+ pluginTriggerMenu: "Eklenti önerileri",
messageAttachments: "Bu iletideki ekler",
fileEmpty: "Eşleşen dosya yok",
fileNoWorkspace: "Dosyalara başvurmak için bir proje açın",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index d83e8a0b9..08f71c300 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -268,6 +268,8 @@ export const zhCN = {
sessionTranscriptEmpty: "无法读取该会话的记录,请重新打开会话后重试。",
fileMenu: "引用文件",
removeFileReference: "移除文件引用 {{name}}",
+ removePluginMark: "移除 {{name}}",
+ pluginTriggerMenu: "插件建议",
messageAttachments: "此消息中的附件",
fileEmpty: "没有匹配的文件",
fileNoWorkspace: "打开项目后即可引用文件",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 5b68be496..5f034ad6f 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -268,6 +268,8 @@ export const zhTW = {
sessionTranscriptEmpty: "無法讀取此工作階段的記錄,請重新開啟後再試一次。",
fileMenu: "引用檔案",
removeFileReference: "移除檔案引用 {{name}}",
+ removePluginMark: "移除 {{name}}",
+ pluginTriggerMenu: "外掛建議",
messageAttachments: "此訊息中的附件",
fileEmpty: "沒有匹配的檔案",
fileNoWorkspace: "開啟專案後即可引用檔案",
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index c5116f59f..fd172445d 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -2181,4 +2181,35 @@ export {
type PluginSlotErrorCode,
type PluginRendererErrorCode,
type PluginSlotRefusal,
+ type PluginComponentSlot,
} from "./renderer.js";
+
+export {
+ PLUGIN_COMPOSER_TRIGGERS,
+ PLUGIN_TRIGGER_MAX_ITEMS,
+ PLUGIN_TRIGGER_TIMEOUT_MS,
+ PLUGIN_MARK_LABEL_MAX_CHARS,
+ PLUGIN_TRIGGER_DETAIL_MAX_CHARS,
+ PLUGIN_MARK_SEND_MAX_BYTES,
+ PLUGIN_DRAFT_MAX_MARKS,
+ PLUGIN_DRAFT_TEXT_MAX_BYTES,
+ PLUGIN_DRAFT_MARK_CHAR,
+ PLUGIN_ATTACHMENT_MAX_BYTES,
+ PLUGIN_ATTACHMENTS_MAX,
+ composerTriggerKey,
+ type PluginComposerTrigger,
+ type PluginTriggerQuery,
+ type PluginTriggerItem,
+ type PluginComposerTriggerRegistration,
+ type PluginDraftMark,
+ type PluginDraftSnapshot,
+ type PluginDraftMarkInput,
+ type PluginReadDraftPayload,
+ type PluginReplaceDraftPayload,
+ type PluginDraftWriteResult,
+ type PluginAttachmentAddPayload,
+ type PluginAttachmentRef,
+ type PluginAttachment,
+ type PluginAttachmentListPayload,
+ type PluginDraftListener,
+} from "./renderer-composer.js";
diff --git a/packages/plugin-sdk/src/renderer-composer.ts b/packages/plugin-sdk/src/renderer-composer.ts
new file mode 100644
index 000000000..fc20a6891
--- /dev/null
+++ b/packages/plugin-sdk/src/renderer-composer.ts
@@ -0,0 +1,175 @@
+/**
+ * Composer contract of the renderer extension (`docs/plugin-plan/ui/composer/`,
+ * `docs/plugin-plan/render/draft/`, `docs/plugin-plan/render/attachments/`).
+ *
+ * - Triggers: a plugin owns one of the fixed symbols `@ # /` and lists items
+ * for it; the host draws the list and turns a picked item into a mark.
+ * - Marks: atomic chips in the draft. A mark shows its `label` and sends its
+ * `send` text in its place.
+ * - Draft: `composer.readDraft`, `composer.insertText`, `composer.replaceDraft`
+ * and the `pi.composer.subscribeDraft` push.
+ * - Attachments: `attachments.add` / `list` / `remove`, content only, each
+ * plugin seeing and touching only its own.
+ */
+
+/** The symbols a plugin can own in the composer; one plugin per symbol. */
+export const PLUGIN_COMPOSER_TRIGGERS = ["@", "#", "/"] as const;
+
+export type PluginComposerTrigger = (typeof PLUGIN_COMPOSER_TRIGGERS)[number];
+
+const FULL_WIDTH_TRIGGERS: Readonly<Record<string, PluginComposerTrigger>> = {
+ "\uFF20": "@",
+ "\uFF03": "#",
+ "\uFF0F": "/",
+};
+
+/**
+ * The trigger a symbol stands for, full-width forms folded to their ASCII
+ * one, or `null` when it is not a trigger symbol.
+ */
+export function composerTriggerKey(value: unknown): PluginComposerTrigger | null {
+ if (typeof value !== "string") return null;
+ const symbol = FULL_WIDTH_TRIGGERS[value] ?? value;
+ return (PLUGIN_COMPOSER_TRIGGERS as readonly string[]).includes(symbol)
+ ? (symbol as PluginComposerTrigger)
+ : null;
+}
+
+/** Items the host keeps from one answer of a trigger; the rest are dropped. */
+export const PLUGIN_TRIGGER_MAX_ITEMS = 50;
+/** How long a trigger may take to answer before its group collapses. */
+export const PLUGIN_TRIGGER_TIMEOUT_MS = 2000;
+/** Longest mark label, in characters. */
+export const PLUGIN_MARK_LABEL_MAX_CHARS = 64;
+/** Longest item detail line, in characters. */
+export const PLUGIN_TRIGGER_DETAIL_MAX_CHARS = 256;
+/** Largest mark `send` text, in UTF-8 bytes. */
+export const PLUGIN_MARK_SEND_MAX_BYTES = 32 * 1024;
+/**
+ * Plugin marks one draft shows. Past it, every further mark joins one host
+ * mark `⧉ +N` that keeps their send text.
+ */
+export const PLUGIN_DRAFT_MAX_MARKS = 8;
+/** Largest `composer.replaceDraft` text, in UTF-8 bytes. */
+export const PLUGIN_DRAFT_TEXT_MAX_BYTES = 256 * 1024;
+/** Where a mark sits in a draft snapshot's `text`. */
+export const PLUGIN_DRAFT_MARK_CHAR = "\uFFFC";
+/** Largest `attachments.add` content, in bytes. */
+export const PLUGIN_ATTACHMENT_MAX_BYTES = 16 * 1024 * 1024;
+/** Attachments one plugin may hold in one draft. */
+export const PLUGIN_ATTACHMENTS_MAX = 20;
+
+/** What a trigger is asked for: the text typed after its symbol. */
+export type PluginTriggerQuery = {
+ readonly trigger: PluginComposerTrigger;
+ readonly query: string;
+};
+
+/**
+ * One row of a trigger's list. Picking it puts a mark in the draft that shows
+ * `label` and sends `send` (`label` when omitted). `detail` is a secondary
+ * line on the row only. An item breaking a limit is dropped from the list.
+ */
+export type PluginTriggerItem = {
+ readonly label: string;
+ readonly send?: string;
+ readonly detail?: string;
+};
+
+/**
+ * `composerTrigger`: own `trigger` (`@`, `#` or `/`, full-width forms
+ * accepted). The host calls `items` as the user types after the symbol at
+ * the start of a line or after whitespace, never during IME composition and
+ * never for text a program wrote. A throw, a rejection or no answer within
+ * `PLUGIN_TRIGGER_TIMEOUT_MS` collapses only this plugin's group.
+ */
+export type PluginComposerTriggerRegistration = {
+ readonly slot: "composerTrigger";
+ readonly trigger: string;
+ readonly items: (
+ query: PluginTriggerQuery,
+ ) => readonly PluginTriggerItem[] | Promise<readonly PluginTriggerItem[]>;
+};
+
+/**
+ * A chip in a draft snapshot, in draft order.
+ * - `host`: the host's own chip (a file, a pasted file, an attachment chip).
+ * `composer.replaceDraft` must keep every one of them.
+ * - `plugin`: a plugin mark. `send` is present only on the caller's own.
+ * - `fold`: the `⧉ +N` mark holding the marks past `PLUGIN_DRAFT_MAX_MARKS`.
+ * `composer.replaceDraft` must keep it too, like a host chip.
+ */
+export type PluginDraftMark =
+ | { readonly id: string; readonly kind: "host"; readonly label: string }
+ | {
+ readonly id: string;
+ readonly kind: "plugin";
+ readonly label: string;
+ readonly pluginId: string;
+ readonly send?: string;
+ }
+ | { readonly id: string; readonly kind: "fold"; readonly label: string; readonly count: number };
+
+/**
+ * The draft as plugins see it. Every chip is one `PLUGIN_DRAFT_MARK_CHAR` in
+ * `text`, matched in order by `marks`. `generation` changes with every change
+ * of the draft, including a switch to another session's draft.
+ */
+export type PluginDraftSnapshot = {
+ readonly text: string;
+ readonly marks: readonly PluginDraftMark[];
+ readonly generation: number;
+};
+
+/** A mark in a replacement: an existing chip by `id`, or a new plugin mark. */
+export type PluginDraftMarkInput =
+ | { readonly id: string }
+ | { readonly label: string; readonly send?: string };
+
+/** `composer.readDraft`: no arguments. */
+export type PluginReadDraftPayload = Record<string, never>;
+
+/**
+ * `composer.replaceDraft`: the whole draft at once. The i-th
+ * `PLUGIN_DRAFT_MARK_CHAR` of `text` takes `marks[i]`, so their counts match.
+ * Refused whole unless `expectedGeneration` is current, the composer does not
+ * have focus, the call runs inside a user's input event (not a timer, a
+ * network answer or a `plugin.call` reply), and every host chip is kept.
+ */
+export type PluginReplaceDraftPayload = {
+ readonly expectedGeneration: number;
+ readonly text: string;
+ readonly marks?: readonly PluginDraftMarkInput[];
+};
+
+/** Draft writes answer with the draft's generation after the write. */
+export type PluginDraftWriteResult = { readonly ok: true; readonly generation: number };
+
+/**
+ * `attachments.add`: content the host stages for the next message. `name`
+ * carries an extension; `content` is the file itself (a string is UTF-8
+ * text), never a path or URL for the host to read. The host keeps the file in
+ * the draft of the session that was active when the call was made; home, with
+ * no session yet, takes none.
+ */
+export type PluginAttachmentAddPayload = {
+ readonly name: string;
+ readonly mimeType: string;
+ readonly content: string | ArrayBuffer | Uint8Array;
+};
+
+export type PluginAttachmentRef = { readonly id: string };
+
+/** One of the caller's own attachments in the active session's draft. */
+export type PluginAttachment = {
+ readonly id: string;
+ readonly name: string;
+ readonly mimeType: string;
+ readonly size: number;
+};
+
+/** `attachments.list`: no arguments. */
+export type PluginAttachmentListPayload = Record<string, never>;
+
+/** Called with the draft snapshot now and after every change; `null` when no composer takes input. */
+export type PluginDraftListener = (snapshot: PluginDraftSnapshot | null) => void;
diff --git a/packages/plugin-sdk/src/renderer.test.ts b/packages/plugin-sdk/src/renderer.test.ts
index da5c2451a..6fb95874d 100644
--- a/packages/plugin-sdk/src/renderer.test.ts
+++ b/packages/plugin-sdk/src/renderer.test.ts
@@ -5,6 +5,7 @@ import {
blockRendererLanguageKey,
slotRegistrationRefusal,
} from "./renderer.js";
+import { PLUGIN_COMPOSER_TRIGGERS, composerTriggerKey } from "./renderer-composer.js";
const PLUGIN = "demo.lab";
const component = () => null;
@@ -22,8 +23,18 @@ describe("renderer vocabulary", () => {
"toolCard",
"blockRenderer",
"composerControl",
+ "composerTrigger",
]);
- expect(PLUGIN_RENDERER_ACTIONS).toEqual(["plugin.call", "composer.insertText"]);
+ expect(PLUGIN_RENDERER_ACTIONS).toEqual([
+ "plugin.call",
+ "composer.insertText",
+ "composer.readDraft",
+ "composer.replaceDraft",
+ "attachments.add",
+ "attachments.list",
+ "attachments.remove",
+ ]);
+ expect(PLUGIN_COMPOSER_TRIGGERS).toEqual(["@", "#", "/"]);
});
});
@@ -35,6 +46,7 @@ describe("slotRegistrationRefusal", () => {
expect(codeOf({ slot: "composerControl", component, positions: ["left", "right"] })).toBeNull();
expect(codeOf({ slot: "toolCard", toolName: "query_db", component }, ["query_db"])).toBeNull();
expect(codeOf({ slot: "blockRenderer", language: "demo.lab:chart", component })).toBeNull();
+ expect(codeOf({ slot: "composerTrigger", trigger: "#", items: () => [] })).toBeNull();
});
it("refuses a slot outside the vocabulary", () => {
@@ -42,7 +54,7 @@ describe("slotRegistrationRefusal", () => {
expect(codeOf("entryExtra")).toBe("PLUGIN_SLOT_UNKNOWN");
expect(codeOf({ component })).toBe("PLUGIN_SLOT_UNKNOWN");
expect(codeOf({ slot: "composerToken", component })).toBe("PLUGIN_SLOT_UNKNOWN");
- expect(codeOf({ slot: "composerTrigger", component })).toBe("PLUGIN_SLOT_UNKNOWN");
+ expect(codeOf({ slot: "composerMark", component })).toBe("PLUGIN_SLOT_UNKNOWN");
});
it("requires a function component", () => {
@@ -110,6 +122,46 @@ describe("slotRegistrationRefusal", () => {
});
});
+describe("composerTrigger registrations", () => {
+ const items = () => [];
+
+ it("takes an items function, not a component", () => {
+ expect(codeOf({ slot: "composerTrigger", trigger: "#" })).toBe("PLUGIN_SLOT_INVALID_COMPONENT");
+ expect(codeOf({ slot: "composerTrigger", trigger: "#", component })).toBe(
+ "PLUGIN_SLOT_INVALID_COMPONENT",
+ );
+ expect(codeOf({ slot: "composerTrigger", trigger: "#", items: [] })).toBe(
+ "PLUGIN_SLOT_INVALID_COMPONENT",
+ );
+ });
+
+ it("keys on one of the fixed symbols, full-width forms included", () => {
+ for (const trigger of ["@", "#", "/", "\uFF20", "\uFF03", "\uFF0F"]) {
+ expect(codeOf({ slot: "composerTrigger", trigger, items })).toBeNull();
+ }
+ for (const trigger of [undefined, "", "$", "##", " #", "#tag", 35]) {
+ expect(codeOf({ slot: "composerTrigger", trigger, items })).toBe("PLUGIN_SLOT_INVALID_KEY");
+ }
+ });
+
+ it("takes no positions", () => {
+ expect(codeOf({ slot: "composerTrigger", trigger: "#", items, positions: ["left"] })).toBe(
+ "PLUGIN_SLOT_INVALID_POSITION",
+ );
+ });
+});
+
+describe("composerTriggerKey", () => {
+ it("folds full-width symbols and refuses everything else", () => {
+ expect(composerTriggerKey("\uFF03")).toBe("#");
+ expect(composerTriggerKey("\uFF20")).toBe("@");
+ expect(composerTriggerKey("\uFF0F")).toBe("/");
+ expect(composerTriggerKey("#")).toBe("#");
+ expect(composerTriggerKey("%")).toBeNull();
+ expect(composerTriggerKey(null)).toBeNull();
+ });
+});
+
describe("blockRendererLanguageKey", () => {
it("normalizes a tag the same way on both sides of the lookup", () => {
expect(blockRendererLanguageKey(" Demo.Lab:Chart ")).toBe("demo.lab:chart");
diff --git a/packages/plugin-sdk/src/renderer.ts b/packages/plugin-sdk/src/renderer.ts
index 74292c30c..4302478d2 100644
--- a/packages/plugin-sdk/src/renderer.ts
+++ b/packages/plugin-sdk/src/renderer.ts
@@ -16,6 +16,9 @@
* - `blockRenderer` — a fenced code block tagged `<pluginId>:<lang>`.
* - `composerControl` — additive controls left and right in the composer
* toolbar.
+ * - `composerTrigger` — the item list behind one of the composer's trigger
+ * symbols; not a component, the host draws the list
+ * (`./renderer-composer.ts`).
*
* Self-dialogs are not a slot: a component draws them itself
* (`docs/plugin-plan/ui/self-dialog/`), into a layer `pi.ui.openLayer` hands
@@ -26,6 +29,20 @@
* host's way; the `renderer.extension` grant is what trusts the code.
*/
+import {
+ composerTriggerKey,
+ type PluginAttachment,
+ type PluginAttachmentAddPayload,
+ type PluginAttachmentListPayload,
+ type PluginAttachmentRef,
+ type PluginComposerTriggerRegistration,
+ type PluginDraftListener,
+ type PluginDraftSnapshot,
+ type PluginDraftWriteResult,
+ type PluginReadDraftPayload,
+ type PluginReplaceDraftPayload,
+} from "./renderer-composer.js";
+
/** Privileged scheme that serves renderer entry modules. */
export const PLUGIN_RENDERER_SCHEME = "plugin-renderer";
@@ -37,6 +54,7 @@ export const PLUGIN_RENDERER_SLOTS = [
"toolCard",
"blockRenderer",
"composerControl",
+ "composerTrigger",
] as const;
export type PluginRendererSlot = (typeof PLUGIN_RENDERER_SLOTS)[number];
@@ -46,6 +64,9 @@ export const PLUGIN_SLOT_POSITIONS = ["left", "right"] as const;
export type PluginSlotPosition = (typeof PLUGIN_SLOT_POSITIONS)[number];
+/** Slots that mount a component; `composerTrigger` hands the host data instead. */
+export type PluginComponentSlot = Exclude<PluginRendererSlot, "composerTrigger">;
+
/** Slots whose registration takes `positions`. */
const POSITIONED_SLOTS: readonly PluginRendererSlot[] = [
"userAction",
@@ -154,7 +175,8 @@ export type PluginSlotRegistration =
| PluginEntryExtraSlotRegistration
| PluginToolCardSlotRegistration
| PluginBlockRendererSlotRegistration
- | PluginComposerControlSlotRegistration;
+ | PluginComposerControlSlotRegistration
+ | PluginComposerTriggerRegistration;
/**
* Outbound actions the host implements. A plugin may dispatch only the words
@@ -162,7 +184,15 @@ export type PluginSlotRegistration =
* refused with `PLUGIN_ACTION_UNKNOWN`, one outside the manifest with
* `PLUGIN_ACTION_UNDECLARED`.
*/
-export const PLUGIN_RENDERER_ACTIONS = ["plugin.call", "composer.insertText"] as const;
+export const PLUGIN_RENDERER_ACTIONS = [
+ "plugin.call",
+ "composer.insertText",
+ "composer.readDraft",
+ "composer.replaceDraft",
+ "attachments.add",
+ "attachments.list",
+ "attachments.remove",
+] as const;
export type PluginRendererActionName = (typeof PLUGIN_RENDERER_ACTIONS)[number];
@@ -178,7 +208,10 @@ export type PluginCallPayload = {
readonly args?: unknown;
};
-/** `composer.insertText`: plain text at the composer caret. */
+/**
+ * `composer.insertText`: plain text at the composer caret, replacing the
+ * selection. It never triggers a list and never carries a mark.
+ */
export type PluginInsertTextPayload = {
readonly text: string;
};
@@ -186,7 +219,15 @@ export type PluginInsertTextPayload = {
/** Payload and result of every action word. */
export type PluginRendererActionMap = {
"plugin.call": { payload: PluginCallPayload; result: unknown };
- "composer.insertText": { payload: PluginInsertTextPayload; result: { ok: true } };
+ "composer.insertText": { payload: PluginInsertTextPayload; result: PluginDraftWriteResult };
+ "composer.readDraft": { payload: PluginReadDraftPayload; result: PluginDraftSnapshot };
+ "composer.replaceDraft": { payload: PluginReplaceDraftPayload; result: PluginDraftWriteResult };
+ "attachments.add": { payload: PluginAttachmentAddPayload; result: PluginAttachmentRef };
+ "attachments.list": {
+ payload: PluginAttachmentListPayload;
+ result: readonly PluginAttachment[];
+ };
+ "attachments.remove": { payload: PluginAttachmentRef; result: { ok: true } };
};
/**
@@ -255,6 +296,17 @@ export type PiRendererApi = {
*/
openLayer(): PluginLayer;
};
+ readonly composer: {
+ /**
+ * Follow the draft instead of polling it: `listener` gets the snapshot
+ * now and after every change (as `composer.readDraft` would answer it),
+ * and `null` while no composer takes input. Requires `composer.readDraft`
+ * in `manifest.rendererActions`, else throws `PLUGIN_ACTION_UNDECLARED`;
+ * throws `PLUGIN_UNLOADED` once this load has ended, which also ends the
+ * subscription. A throwing listener is logged and stays subscribed.
+ */
+ subscribeDraft(listener: PluginDraftListener): PluginDisposer;
+ };
readonly dispatch: PluginRendererDispatch;
};
@@ -268,9 +320,9 @@ export type PiRendererModule = {
export type PluginSlotErrorCode =
/** `slot` is not in `PLUGIN_RENDERER_SLOTS`. */
| "PLUGIN_SLOT_UNKNOWN"
- /** `component` is not a function. */
+ /** `component` (or a trigger's `items`) is not a function. */
| "PLUGIN_SLOT_INVALID_COMPONENT"
- /** A keyed slot's `toolName` / `language` is malformed. */
+ /** A keyed slot's `toolName` / `language` / `trigger` is malformed. */
| "PLUGIN_SLOT_INVALID_KEY"
/** `positions` is malformed, or given to a slot without sides. */
| "PLUGIN_SLOT_INVALID_POSITION"
@@ -291,8 +343,26 @@ export type PluginRendererErrorCode =
| "PLUGIN_ACTION_UNDECLARED"
/** The payload does not have the word's shape or exceeds its limit. */
| "PLUGIN_ACTION_INVALID_PAYLOAD"
- /** No composer is mounted to take the action. */
+ /** No composer takes input now: none is mounted, or it is blocked. */
| "PLUGIN_ACTION_NO_COMPOSER"
+ /** `composer.replaceDraft`: `expectedGeneration` is not the current one. */
+ | "PLUGIN_DRAFT_STALE"
+ /** `composer.replaceDraft`: the composer has focus; the user is typing. */
+ | "PLUGIN_DRAFT_FOCUSED"
+ /** `composer.replaceDraft`: not called inside a user's input event. */
+ | "PLUGIN_DRAFT_REMOTE"
+ /** `composer.replaceDraft`: the replacement drops a host chip. */
+ | "PLUGIN_DRAFT_ANCHOR"
+ /** `attachments.add`: the content is a path or URL, not the file. */
+ | "PLUGIN_ATTACHMENT_REFERENCE_REFUSED"
+ /** `attachments.add`: over the size ceiling or this plugin's count. */
+ | "PLUGIN_ATTACHMENT_LIMIT"
+ /** `attachments.add`: no session takes it (home), or the session changed meanwhile. */
+ | "PLUGIN_ATTACHMENT_NO_SESSION"
+ /** `attachments.remove`: no attachment of this plugin has that id. */
+ | "PLUGIN_ATTACHMENT_NOT_FOUND"
+ /** `attachments.add`: the host could not stage the file. */
+ | "PLUGIN_ATTACHMENT_FAILED"
/** This load has ended: nothing registers, injects or dispatches through it. */
| "PLUGIN_UNLOADED"
/** `plugin.call`: the method is not declared, or `onRendererCall` is missing. */
@@ -352,6 +422,7 @@ export function slotRegistrationRefusal(
if (typeof slot !== "string" || !(PLUGIN_RENDERER_SLOTS as readonly string[]).includes(slot)) {
return refusal("PLUGIN_SLOT_UNKNOWN", `unknown slot ${describe(slot)}`);
}
+ if (slot === "composerTrigger") return composerTriggerRefusal(candidate);
if (typeof candidate.component !== "function") {
return refusal("PLUGIN_SLOT_INVALID_COMPONENT", `${slot} component must be a function`);
}
@@ -399,3 +470,19 @@ export function slotRegistrationRefusal(
}
return null;
}
+
+function composerTriggerRefusal(candidate: Record<string, unknown>): PluginSlotRefusal | null {
+ if (typeof candidate.items !== "function") {
+ return refusal("PLUGIN_SLOT_INVALID_COMPONENT", "composerTrigger items must be a function");
+ }
+ if (candidate.positions !== undefined) {
+ return refusal("PLUGIN_SLOT_INVALID_POSITION", "composerTrigger takes no positions");
+ }
+ if (!composerTriggerKey(candidate.trigger)) {
+ return refusal(
+ "PLUGIN_SLOT_INVALID_KEY",
+ `composerTrigger trigger must be "@", "#" or "/" (got ${describe(candidate.trigger)})`,
+ );
+ }
+ return null;
+}
diff --git a/packages/shared/src/composer-trigger.test.ts b/packages/shared/src/composer-trigger.test.ts
index 5c69f7581..36fdff222 100644
--- a/packages/shared/src/composer-trigger.test.ts
+++ b/packages/shared/src/composer-trigger.test.ts
@@ -227,6 +227,19 @@ describe("compact file references", () => {
);
});
+ it("resolves a plugin mark to the text it sends, never to a path", () => {
+ const references = [
+ { path: "", token: "\uE001", plugin: { send: "Issue #42: crash on start" } },
+ { path: "src/a.ts", token: "\uE002" },
+ { path: "", token: "\uE003", plugin: { send: "#7 #8" } },
+ ];
+ expect(
+ serializeInlineComposerFileReferences("see \uE001\uE002 and \uE003", references),
+ ).toBe("see Issue #42: crash on start @src/a.ts and #7 #8");
+ // A mark is inline only: once its chip is gone it sends nothing.
+ expect(serializeComposerFileReferences("gone", references.slice(0, 1))).toBe("gone");
+ });
+
it("does not serialize an inline reference after its token is removed", () => {
expect(
serializeComposerFileReferences("the token was removed", [
diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.ts
index a3f6d8917..d11a25e60 100644
--- a/packages/shared/src/composer-trigger.ts
+++ b/packages/shared/src/composer-trigger.ts
@@ -171,13 +171,16 @@ export function fileReferenceLabel(path: string, preferredName?: string): string
return normalized.slice(normalized.lastIndexOf("/") + 1) || candidate;
}
+/** What serialization reads of a reference's plugin part (`send` of a mark). */
+type ComposerReferencePluginPart = { readonly kind?: string; readonly send?: string };
+
/**
* Serialize renderer-owned file references only at send time. The textarea can
* stay compact while the persisted/model-facing prompt keeps exact @ paths.
*/
export function serializeComposerFileReferences(
draft: string,
- references: ReadonlyArray<{ path: string; token?: string }>,
+ references: ReadonlyArray<{ path: string; token?: string; plugin?: ComposerReferencePluginPart }>,
): string {
const content = serializeInlineComposerFileReferences(draft, references);
const paths = references
@@ -193,17 +196,20 @@ export function serializeComposerFileReferences(
/**
* Resolve only inline generated tokens (legacy @name strings or single
* sentinel characters backing atomic chips). Each resolved token keeps one
- * separating space so adjacent chips never fuse their @paths together.
+ * separating space so adjacent chips never fuse their @paths together. A
+ * plugin mark's token resolves to the text it sends (`plugin.send`) instead
+ * of a path.
*/
export function serializeInlineComposerFileReferences(
draft: string,
- references: ReadonlyArray<{ path: string; token?: string }>,
+ references: ReadonlyArray<{ path: string; token?: string; plugin?: ComposerReferencePluginPart }>,
): string {
let content = draft;
for (const reference of references) {
const token = reference.token?.trim();
if (!token || !content.includes(token)) continue;
- const insert = formatFileInsert(reference.path, "file").trim();
+ const send = reference.plugin?.send;
+ const insert = typeof send === "string" ? send : formatFileInsert(reference.path, "file").trim();
let index = content.indexOf(token);
while (index !== -1) {
const nextChar = content[index + token.length];