mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 00:48:44 +01:00
feat(antigravity): /plan selects Plan mode and keeps Antigravity read-only while planning (#22727)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plan mode lets a person ask an agent for a plan, review it as the task's Plan document, and accept it before any work starts > - People who use Google Antigravity agents type `/plan <request>`, as they do in other agent tools. Paperclip sent that text to the agent, and #22701 correctly neutralised it, so nothing happened > - An Antigravity run in Plan mode was also not read-only: the agent could still edit files and run commands while it "planned" > - This pull request makes a leading `/plan` in the composer select Plan mode, and keeps an Antigravity Plan-mode run read-only at its permission prompt > - The benefit is that `/plan` with an Antigravity agent gives the normal Paperclip plan flow (Plan document, accept, then execution on the same task), and planning cannot change the workspace ## Linked Issues or Issue Description Refs #22701 **What happened?** A person wrote `/plan add greeting.txt` to a Google Antigravity agent. The agent did not plan. In Plan mode the Antigravity agent could still edit files and run commands. **What did you expect?** `/plan <request>` starts Plan mode. The agent researches and proposes a plan in the task's Plan document. It does not change files until the person accepts the plan. **Steps to reproduce** 1. Assign a task to a Google Antigravity agent. 2. Write `/plan Add a file greeting.txt containing hello`. 3. See that the task stays in Auto mode, and that the agent creates the file. ## What Changed - Task composer: a leading `/plan` in a comment or in a new task selects Plan mode and sends the rest of the message without the command. `/plan` alone only switches the mode. The slash menu offers "Plan". A `/plan` anywhere else in the message (quoted, pasted, fenced, mid-sentence) stays ordinary text and does not change the mode. This is the typed form of the existing Plan mode control, so it works the same for every agent. - Antigravity runner (`antigravity-plan-mode.ts`, wired in `acpx-runtime-adapter.ts` and `runtime-host.ts`): when Paperclip runs an Antigravity task in Plan mode (the existing read-only task policy), the permission prompt fails closed. It allows only (a) the 1.5.2 server's built-in research tools (file read, search, directory listing, page read), named by the exact `Run <tool>?` prompt title, when the reported kind also matches that tool, and (b) the tools the runner's own Paperclip bridge registered for this run, on the runner-owned server named `paperclip`. The provider's reported kind alone never grants a read, and no other MCP server is trusted, runner-owned or not. It refuses file edits, terminal commands and everything else. Paperclip's server applies its Plan-mode rules to its own tools, and the agent writes the Plan document through them. - Composer command parsing moved to `ui/src/components/task-chat/composer-commands.ts`. `/goal` and `/plan` both use the shared rule. Both submit paths use one `/plan` decision: a bare `/plan` sends (in Plan mode) only when an attachment can be sent without text; otherwise it only selects Plan mode. A composer without Plan mode (the dashboard chat starter) keeps `/plan` as text. - Follow-up, not in this PR: the Kimi read-only gate (`kimiReadOnlyPermissionAllowed`) trusts every runner-owned MCP server by title prefix. It should get the same binding to the Paperclip bridge's registered tools. - No change to the #22701 guard. Every `/plan`, `/logout` and `/usage` that would reach the Antigravity server is still neutralised. - No change to the Antigravity admission patch, profile or closure digests. No shared contract change. ### Why not the native `/plan` of Antigravity 1.5.2 I checked the pinned 1.5.2 server and SDK sources and ran it live: - The server has no plan session mode (only `default`, `auto_edit`, `yolo`) and no plan config option. Its only route is the `/plan` text command, which it turns into an SDK slash-command object. - Live on 1.5.2 (Google sign-in, `gemini-3.8-flash-low`), a task with `Please /plan this ...` reached the model as `Please/BuiltinSlashCommandName.PLAN this ...`. The SDK sent the enum's string form instead of `plan`, so the harness did not enter planning mode. Over 61 native steps (about 5 minutes) the agent wrote no plan artifact, ran terminal commands, and searched the file system for that unknown name. I stopped the run. - A working native path needs a change inside the runtime (for example in the owned admission patch), which re-pins the closures for every platform and needs re-qualification. This PR does not do that. Paperclip's own Plan mode gives the user-visible result now, with no re-pin. ### Source of trust for slash commands (reused by `/swarm`) - `parseLeadingUserCommand(text, allowlist)` in `packages/shared/src/leading-user-command.ts` is the one rule. It returns `{ command, argument }` or `null`. - Trusted text: only what the signed-in user typed and submitted in the task composer. That is a comment body or the body of a new task. Conversations (chat) do not use it for `/plan`. - Never trusted: agent comments, chat or connector messages, API-posted text, issue text written by someone else, quoted or pasted parts, and every prompt Paperclip builds for an agent. These stay text, and the #22701 guard still neutralises any native command in them. - Inside trusted text, only a command at the very start counts: optional whitespace, `/name`, then whitespace or the end. The name is exact and lower-case and must be in the allowlist. Only `plan` is enabled. Whitespace follows the Antigravity server's Python rules (U+001C-U+001F count; U+FEFF does not). - A recognised command becomes a structured action (here: Plan mode). It never reaches an agent as command text. - Tests cover: leading whitespace and newlines, a command not at the start, quoted, fenced, forwarded and wrapped content, a neutralised command, case, `/planning`, `/plans`, paths and URLs, Python vs JavaScript whitespace, and the allowlist. ## Verification - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/acpx/antigravity-plan-mode.test.ts src/drivers/acpx/acpx-runtime-adapter.test.ts src/drivers/acpx/antigravity-native-commands.test.ts src/drivers/acpx/antigravity-admission.test.ts`: 250 passed. - `pnpm --filter @paperclipai/shared exec vitest run src/leading-user-command.test.ts`: 8 passed (red first: module missing). - `pnpm --filter @paperclipai/ui exec vitest run src/components/task-chat/TaskChatComposer.test.tsx src/components/MarkdownEditor.autocomplete.test.tsx`: all passed (TaskChatComposer 155). - Red before the fix: the adapter test showed an Antigravity Plan-mode run approved a file write and a terminal command (`allow_once`), and the four composer `/plan` tests failed. The negative test (a `/plan` inside the message stays text) passed before and after. - Runner and UI typecheck pass (`tsc --noEmit`; the UI's only errors are the existing ungenerated Storybook catalog files). - `pnpm verify` returned exit 2 (runner files outside the local test graph), so required CI supplies the broad coverage. - Live, on THIS branch: a local instance running this branch, Google sign-in, `gemini-3.8-flash-low`, driven in the browser through the task composer: 1. `/plan Create a file named plan-proof.txt containing the single line OK` in a new task: the task was created in Plan mode with the command removed. Plan run 3 min 34 s, terminal state **succeeded** (the agent handed in through `paperclip_finish`; run result accepted, waiting for plan approval). The Plan document and a Confirm / Request changes card appeared. One `ls -la` was refused by the read-only gate. No file was written. 2. Request changes ("Name the file plan-proof-2.txt instead."): revision run 28 s, succeeded. Plan document revision 2 named the new file; a new Confirm / Request changes card appeared. Still no file. 3. Confirm: execution run 55 s, succeeded; task Done; `plan-proof-2.txt` contains exactly `OK` plus a newline. 4. Normal task whose text contains a pasted `"we usually /plan things like this first"`: created in standard mode, text unchanged; run 68 s, succeeded, Done; `negative-proof.txt` = `NEG`; no refused tool call. 5. Dashboard "Start a chat" box: NOT run live. The box renders only with an experimental instance setting that is off on this instance, and I did not change instance settings. A unit test covers it (a composer without Plan mode keeps `/plan` as text). 6. Stop during a Plan-mode run: the run was cancelled about 1 s after Stop and did not revive (no new run for over 3 min); no file. Killing only the native Antigravity server process mid Plan-mode run: the run failed with a provider error, showed "Continuing automatically", and a continuation run started 36 s later and settled (succeeded, 3 min 17 s, response wake). No duplicate comments; the Plan document has one revision; no file written; the gate refused one shell command in each run. - Found live, NOT fixed here: in the recovered run of step 6 the model settled with "waiting for plan review" but did not open the Confirm card (in steps 1 and 2 it did). Paperclip creates that card automatically only from a harness's own plan proposal (Codex, Claude). For Antigravity it depends on the agent. Recommended follow-up: when a Plan-mode run settles with a new plan revision and no pending plan confirmation, the server opens the card itself. - To be clear: this is not Antigravity's native plan mode. Native plan mode on runtime 1.5.2 does not work (see above). This PR gives Paperclip's Plan mode, started by a trusted `/plan`, with the Antigravity run held read-only. ## Risks - Low to medium. Plan mode for Antigravity now refuses terminal commands, so the agent researches with its file read and search tools. A planner that relied on shell reads must use those tools instead. - Google Workspace accounts whose admin policy lets terminal commands run in a sandbox without a prompt skip the permission prompt for commands. That path cannot be blocked here. Personal Google accounts and API keys always prompt. - `/plan` as the first word of a message now selects Plan mode for every agent. To send the literal text, write `\/plan` or put other text first. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edit, browser automation not used), in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b6f1b7b4af
commit
18aa2b353d
14 files changed
+566
-70
No files matched your search
@@ -9,7 +9,8 @@ import {
|
||||
buildSkillMentionHref,
|
||||
instanceExperimentalSettingsSchema,
|
||||
} from "@paperclipai/shared";
|
||||
import { parseRunnerGoalCommand, TaskChatComposer } from "./TaskChatComposer";
|
||||
import { parsePlanCommand, parseRunnerGoalCommand, TaskChatComposer } from "./TaskChatComposer";
|
||||
import { planSubmission } from "./composer-commands";
|
||||
import { ComposerAddMenu } from "./ComposerAddMenu";
|
||||
import { QuestionForm } from "./QuestionForm";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
@@ -2002,6 +2003,128 @@ describe("TaskChatComposer", () => {
|
||||
expect(editable().textContent).toBe(`[/deploy](${SLASH_HREF}) `);
|
||||
});
|
||||
|
||||
describe("/plan command", () => {
|
||||
it("matches only the user's leading /plan token", () => {
|
||||
expect(parsePlanCommand(" /plan Add a greeting file ")).toEqual({ matched: true, request: "Add a greeting file" });
|
||||
expect(parsePlanCommand("/plan")).toEqual({ matched: true, request: "" });
|
||||
expect(parsePlanCommand("/plan\n\nLine one\nLine two")).toEqual({ matched: true, request: "Line one\nLine two" });
|
||||
expect(parsePlanCommand("[/pl](</plan Add a greeting file>)")).toEqual({ matched: true, request: "Add a greeting file" });
|
||||
// A /plan anywhere else is ordinary text, including quoted or pasted content.
|
||||
expect(parsePlanCommand("Please /plan this first")).toEqual({ matched: false });
|
||||
expect(parsePlanCommand("> /plan from a pasted email")).toEqual({ matched: false });
|
||||
expect(parsePlanCommand("```\n/plan\n```")).toEqual({ matched: false });
|
||||
expect(parsePlanCommand("\\/plan ordinary text")).toEqual({ matched: false });
|
||||
expect(parsePlanCommand("/planning notes")).toEqual({ matched: false });
|
||||
});
|
||||
|
||||
it("sends the request in Plan mode without the command", async () => {
|
||||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange });
|
||||
typeText("/plan Add a greeting file");
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||||
expect(onAdd).toHaveBeenCalledWith("Add a greeting file", undefined, undefined, undefined, expect.any(String));
|
||||
expect(onWorkModeChange.mock.invocationCallOrder[0]).toBeLessThan(onAdd.mock.invocationCallOrder[0]!);
|
||||
});
|
||||
|
||||
it("switches to Plan mode without sending when no request follows", async () => {
|
||||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() });
|
||||
typeText("/plan");
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(onAdd).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")).toBe("planning");
|
||||
expect(editable().textContent).toBe("");
|
||||
});
|
||||
|
||||
it("leaves a /plan inside the message as ordinary text", async () => {
|
||||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange });
|
||||
typeText("Please /plan this first");
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(onWorkModeChange).not.toHaveBeenCalled();
|
||||
expect(onAdd).toHaveBeenCalledWith("Please /plan this first", undefined, undefined, undefined, expect.any(String));
|
||||
});
|
||||
|
||||
it("offers Plan in the slash menu, except while editing a queued message", async () => {
|
||||
const planOffered = () => Array.from(document.body.querySelectorAll<HTMLButtonElement>(
|
||||
'[data-testid="mention-autocomplete-menu"] button[type="button"]')).some(node => node.textContent?.includes("/plan"));
|
||||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||||
typeText("/pl");
|
||||
await placeCaretAtEnd();
|
||||
expect(planOffered()).toBe(true);
|
||||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onWorkModeChange={vi.fn()}
|
||||
queuedEdit={{ commentId: "queued", body: "" }} onSaveQueuedEdit={vi.fn()} />);
|
||||
typeText("/pl");
|
||||
await placeCaretAtEnd();
|
||||
expect(planOffered()).toBe(false);
|
||||
});
|
||||
|
||||
it("decides a bare /plan the same way for both submit paths", () => {
|
||||
expect(planSubmission("/plan", false)).toEqual({ kind: "switch_mode" });
|
||||
expect(planSubmission("/plan", true)).toEqual({ kind: "send", text: "" });
|
||||
expect(planSubmission("/plan Ship it", false)).toEqual({ kind: "send", text: "Ship it" });
|
||||
expect(planSubmission("Ship it /plan", true)).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("sends a bare /plan with an attachment as the request in Plan mode", async () => {
|
||||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||||
const id = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||||
const onAttachImage = vi.fn().mockResolvedValue({ id, contentPath: `/api/attachments/${id}/content`, originalFilename: "spec.txt" });
|
||||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange, onAttachImage });
|
||||
typeText("/plan");
|
||||
pasteFiles([new File(["spec"], "spec.txt", { type: "text/plain" })]);
|
||||
await flushAsync();
|
||||
flushSync(() => sendButton().click());
|
||||
await flushAsync();
|
||||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||||
expect(onAdd).toHaveBeenCalledOnce();
|
||||
expect(onAdd.mock.calls[0]?.[0]).not.toContain("/plan");
|
||||
expect(onAdd.mock.calls[0]?.[3]).toEqual([id]);
|
||||
});
|
||||
|
||||
it("creates a task from a bare /plan with an image only when the task may have no text", async () => {
|
||||
const image = new File(["png"], "screen.png", { type: "image/png" });
|
||||
const creation = { value: "/plan", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined), submitLabel: "Create",
|
||||
onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn(), images: [{ id: "screen", name: image.name, file: image }] };
|
||||
render(<TaskChatComposer creation={{ ...creation, canSubmitWithoutBody: true }} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(creation.onSubmit).toHaveBeenCalledWith("", "planning", null);
|
||||
const onWorkModeChange = vi.fn();
|
||||
const bare = { ...creation, onSubmit: vi.fn() };
|
||||
render(<TaskChatComposer creation={bare} workMode="standard" onWorkModeChange={onWorkModeChange} />);
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(bare.onSubmit).not.toHaveBeenCalled();
|
||||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||||
});
|
||||
|
||||
it("keeps /plan as text in a composer that has no Plan mode", async () => {
|
||||
const creation = { value: "/plan Add a greeting file", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||||
submitLabel: "Start", onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn() };
|
||||
render(<TaskChatComposer creation={creation} workMode="standard" />);
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(creation.onSubmit).toHaveBeenCalledWith("/plan Add a greeting file", "standard", null);
|
||||
});
|
||||
|
||||
it("creates a new task in Plan mode", async () => {
|
||||
const creation = { value: "/plan Add a greeting file", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||||
submitLabel: "Create", onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn() };
|
||||
render(<TaskChatComposer creation={creation} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||||
pressKey("Enter", { metaKey: true });
|
||||
await flushAsync();
|
||||
expect(creation.onSubmit).toHaveBeenCalledWith("Add a greeting file", "planning", null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("/goal action commands", () => {
|
||||
const capability = {
|
||||
availability: "available" as const,
|
||||
|
||||
@@ -72,6 +72,7 @@ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import type { MentionOption } from "@/components/MarkdownEditor";
|
||||
import type { IssueAttachment, IssueWorkMode } from "@paperclipai/shared";
|
||||
import type { RunnerGoalCapability } from "@paperclipai/shared";
|
||||
import { parseRunnerGoalCommand, planSubmission, type RunnerGoalComposerCommand } from "./composer-commands";
|
||||
import type { ActionCommandOption } from "@/context/EditorAutocompleteContext";
|
||||
import { TaskChatComposerTakeoverActionsContext } from "./TaskChatComposerTakeoverContext";
|
||||
|
||||
@@ -189,68 +190,8 @@ interface TaskChatComposerProps {
|
||||
) => Promise<void> | void;
|
||||
}
|
||||
|
||||
export type RunnerGoalComposerCommand =
|
||||
| { action: "focus" }
|
||||
| { action: "create"; objective: string }
|
||||
| { action: "edit" }
|
||||
| { action: "pause" }
|
||||
| { action: "resume" }
|
||||
| { action: "clear" };
|
||||
|
||||
export type ParsedRunnerGoalCommand =
|
||||
| { matched: false }
|
||||
| { matched: true; command: RunnerGoalComposerCommand }
|
||||
| { matched: true; error: string };
|
||||
|
||||
function normalizeRunnerGoalCommandText(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
// MDXEditor's link extension can reinterpret a selected action command plus
|
||||
// its subsequently typed argument as one relative autolink. Accept only the
|
||||
// exact whole-document shape it generates so the action still cannot fall
|
||||
// through as a comment. Ordinary Markdown links remain ordinary comments.
|
||||
const relativeAutolink = trimmed.match(
|
||||
/^\[\/(?:go(?:al)?)?[ \t\u00a0]*\]\(<(\/goal(?:[ \t\u00a0].*)?)>\)$/s,
|
||||
);
|
||||
if (relativeAutolink) return relativeAutolink[1]!.replaceAll("\u00a0", " ");
|
||||
|
||||
const encodedAutolink = trimmed.match(
|
||||
/^\[\/(?:go(?:al)?)?[ \t\u00a0]*\]\((\/goal(?:%20|%C2%A0).*)\)$/s,
|
||||
);
|
||||
if (encodedAutolink) {
|
||||
try {
|
||||
return decodeURIComponent(encodedAutolink[1]!).replaceAll("\u00a0", " ");
|
||||
} catch {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
return trimmed.replaceAll("\u00a0", " ");
|
||||
}
|
||||
|
||||
export function parseRunnerGoalCommand(value: string): ParsedRunnerGoalCommand {
|
||||
const trimmed = normalizeRunnerGoalCommandText(value);
|
||||
if (!trimmed) return { matched: false };
|
||||
const firstWhitespace = trimmed.search(/\s/);
|
||||
const firstToken =
|
||||
firstWhitespace === -1 ? trimmed : trimmed.slice(0, firstWhitespace);
|
||||
if (firstToken !== "/goal") return { matched: false };
|
||||
const remainder =
|
||||
firstWhitespace === -1 ? "" : trimmed.slice(firstWhitespace).trim();
|
||||
if (!remainder) return { matched: true, command: { action: "focus" } };
|
||||
const [subcommand, ...extra] = remainder.split(/\s+/);
|
||||
if (["edit", "pause", "resume", "clear"].includes(subcommand)) {
|
||||
if (extra.length > 0) {
|
||||
return {
|
||||
matched: true,
|
||||
error: `/goal ${subcommand} does not accept extra arguments.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
matched: true,
|
||||
command: { action: subcommand as "edit" | "pause" | "resume" | "clear" },
|
||||
};
|
||||
}
|
||||
return { matched: true, command: { action: "create", objective: remainder } };
|
||||
}
|
||||
export { parsePlanCommand, parseRunnerGoalCommand } from "./composer-commands";
|
||||
export type { ParsedRunnerGoalCommand, RunnerGoalComposerCommand } from "./composer-commands";
|
||||
|
||||
function identityInitials(label: string): string {
|
||||
const parts = label.trim().split(/\s+/).filter(Boolean);
|
||||
@@ -681,6 +622,14 @@ export function TaskChatComposer({
|
||||
const effectivePlaceholder = queuedEdit
|
||||
? "Edit queued message…"
|
||||
: (placeholder ?? modePlaceholder(pendingMode, assigneeName, mobile));
|
||||
const planCommandOption: ActionCommandOption = {
|
||||
id: "action:plan",
|
||||
kind: "action",
|
||||
command: "plan",
|
||||
name: "Plan",
|
||||
description: "Plan before acting. Nothing changes until you accept the plan.",
|
||||
aliases: ["plan", "planning"],
|
||||
};
|
||||
const goalUnavailable = runnerGoalCapability?.availability !== "available";
|
||||
const goalCommandOption: ActionCommandOption = {
|
||||
id: "action:goal",
|
||||
@@ -915,12 +864,22 @@ export function TaskChatComposer({
|
||||
async function submit() {
|
||||
if (disabled || (pause && !canResetPausedConversation)) return;
|
||||
if (creation) {
|
||||
// Only a composer that offers Plan mode reads /plan; elsewhere it stays text.
|
||||
const plan = onWorkModeChange
|
||||
? planSubmission(bodyRef.current, Boolean(creation.canSubmitWithoutBody && creation.images?.length))
|
||||
: ({ kind: "none" } as const);
|
||||
if (plan.kind === "switch_mode" && !submittingRef.current) {
|
||||
changeMode("planning");
|
||||
creation.onChange("");
|
||||
editorRef.current?.clear();
|
||||
return;
|
||||
}
|
||||
if (submittingRef.current || uploadPending || uploadFailed || creation.submitDisabled || (!bodyRef.current.trim() && !creation.canSubmitWithoutBody)) return;
|
||||
submittingRef.current = true;
|
||||
setSubmitting(true);
|
||||
setActionError(null);
|
||||
try {
|
||||
await creation.onSubmit(bodyRef.current, pendingMode, runSettings);
|
||||
await creation.onSubmit(plan.kind === "send" ? plan.text : bodyRef.current, plan.kind === "send" ? "planning" : pendingMode, runSettings);
|
||||
} catch (error) {
|
||||
setActionError(describeError(error, { action: "create the task" }).body);
|
||||
} finally {
|
||||
@@ -940,7 +899,20 @@ export function TaskChatComposer({
|
||||
const submittedAttachments = attachmentsRef.current;
|
||||
const submittedAssignee = pendingAssigneeRef.current;
|
||||
const submittedModeGeneration = modeChoiceGeneration.current;
|
||||
const trimmed = submittedBody.trim();
|
||||
// Plan mode belongs to tasks; a queued edit keeps its exact text.
|
||||
const planCommand = queuedEdit || conversationMode || !onWorkModeChange
|
||||
? ({ kind: "none" } as const)
|
||||
: planSubmission(submittedBody, attachedRefs.length > 0);
|
||||
if (planCommand.kind === "switch_mode") {
|
||||
changeMode("planning");
|
||||
bodyRef.current = "";
|
||||
if (draftKey) clearDraft(draftKey);
|
||||
setBody("");
|
||||
editorRef.current?.clear();
|
||||
return;
|
||||
}
|
||||
const sendMode = planCommand.kind === "send" ? "planning" : pendingMode;
|
||||
const trimmed = planCommand.kind === "send" ? planCommand.text : submittedBody.trim();
|
||||
const goalCommand = queuedEdit
|
||||
? ({ matched: false } as const)
|
||||
: parseRunnerGoalCommand(submittedBody);
|
||||
@@ -1068,8 +1040,8 @@ export function TaskChatComposer({
|
||||
onCancelQueuedEdit?.();
|
||||
return;
|
||||
}
|
||||
if (pendingMode !== workMode && onWorkModeChange) {
|
||||
await onWorkModeChange(pendingMode);
|
||||
if (sendMode !== workMode && onWorkModeChange) {
|
||||
await onWorkModeChange(sendMode);
|
||||
}
|
||||
const retainedAfterMode = draftKey ? loadDraftSubmission(draftKey) : null;
|
||||
if (retainedAfterMode) {
|
||||
@@ -1437,11 +1409,13 @@ export function TaskChatComposer({
|
||||
}
|
||||
readOnly={disabled || !!uncertainSubmission || Boolean(creation && (submitting || creation.readOnly))}
|
||||
mentions={mentions}
|
||||
actionCommands={creation ? [] : conversationMode ? [{
|
||||
actionCommands={conversationMode ? [{
|
||||
id: "action:new", kind: "action", command: "new", name: "New session",
|
||||
description: "Start fresh context here, preserving conversation history.", aliases: ["new"],
|
||||
disabled,
|
||||
}] : [goalCommandOption]}
|
||||
}] : creation ? (onWorkModeChange ? [planCommandOption] : [])
|
||||
// A queued edit keeps its exact text, so /plan cannot select Plan mode there.
|
||||
: onWorkModeChange && !queuedEdit ? [planCommandOption, goalCommandOption] : [goalCommandOption]}
|
||||
onSubmit={() => void submit()}
|
||||
submitKey={submitKey}
|
||||
fileDropTarget="parent"
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { parseLeadingUserCommand } from "@paperclipai/shared";
|
||||
|
||||
/**
|
||||
* Slash commands typed in the task composer. What the signed-in user submits
|
||||
* here is the user-authored text `parseLeadingUserCommand` requires, and that
|
||||
* shared function is the one rule for a leading command. This module only
|
||||
* undoes editor artifacts first and turns a recognised command into an action.
|
||||
*/
|
||||
|
||||
export type RunnerGoalComposerCommand =
|
||||
| { action: "focus" }
|
||||
| { action: "create"; objective: string }
|
||||
| { action: "edit" }
|
||||
| { action: "pause" }
|
||||
| { action: "resume" }
|
||||
| { action: "clear" };
|
||||
|
||||
export type ParsedRunnerGoalCommand =
|
||||
| { matched: false }
|
||||
| { matched: true; command: RunnerGoalComposerCommand }
|
||||
| { matched: true; error: string };
|
||||
|
||||
function normalizeActionCommandText(value: string, command: "goal" | "plan"): string {
|
||||
const trimmed = value.trim();
|
||||
// MDXEditor's link extension can reinterpret a selected action command plus
|
||||
// its subsequently typed argument as one relative autolink. Accept only the
|
||||
// exact whole-document shape it generates so the action still cannot fall
|
||||
// through as a comment. Ordinary Markdown links remain ordinary comments.
|
||||
// The label is any prefix of the command typed before it was selected.
|
||||
const label = command === "goal" ? "(?:go(?:al)?)?" : "(?:p(?:l(?:an?)?)?)?";
|
||||
const relativeAutolink = trimmed.match(
|
||||
new RegExp(`^\\[\\/${label}[ \\t\\u00a0]*\\]\\(<(\\/${command}(?:[ \\t\\u00a0].*)?)>\\)$`, "s"),
|
||||
);
|
||||
if (relativeAutolink) return relativeAutolink[1]!.replaceAll(" ", " ");
|
||||
|
||||
const encodedAutolink = trimmed.match(
|
||||
new RegExp(`^\\[\\/${label}[ \\t\\u00a0]*\\]\\((\\/${command}(?:%20|%C2%A0).*)\\)$`, "s"),
|
||||
);
|
||||
if (encodedAutolink) {
|
||||
try {
|
||||
return decodeURIComponent(encodedAutolink[1]!).replaceAll(" ", " ");
|
||||
} catch {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
return trimmed.replaceAll(" ", " ");
|
||||
}
|
||||
|
||||
/**
|
||||
* `/plan <request>` is the typed form of the Plan mode control: the request is
|
||||
* sent in Plan mode, without the command. A `/plan` anywhere else stays text.
|
||||
*/
|
||||
export function parsePlanCommand(value: string): { matched: false } | { matched: true; request: string } {
|
||||
const command = parseLeadingUserCommand(normalizeActionCommandText(value, "plan"), ["plan"]);
|
||||
return command ? { matched: true, request: command.argument } : { matched: false };
|
||||
}
|
||||
|
||||
export type PlanSubmission =
|
||||
| { kind: "none" }
|
||||
/** Select Plan mode and send nothing. */
|
||||
| { kind: "switch_mode" }
|
||||
/** Send this text (possibly empty) in Plan mode. */
|
||||
| { kind: "send"; text: string };
|
||||
|
||||
/**
|
||||
* The one decision both submit paths use. A bare `/plan` sends only when the
|
||||
* message still carries something to plan from (an attachment that can be
|
||||
* sent without text); otherwise it only selects Plan mode.
|
||||
*/
|
||||
export function planSubmission(value: string, canSendWithoutText: boolean): PlanSubmission {
|
||||
const plan = parsePlanCommand(value);
|
||||
if (!plan.matched) return { kind: "none" };
|
||||
if (!plan.request && !canSendWithoutText) return { kind: "switch_mode" };
|
||||
return { kind: "send", text: plan.request };
|
||||
}
|
||||
|
||||
export function parseRunnerGoalCommand(value: string): ParsedRunnerGoalCommand {
|
||||
const command = parseLeadingUserCommand(normalizeActionCommandText(value, "goal"), ["goal"]);
|
||||
if (!command) return { matched: false };
|
||||
const remainder = command.argument;
|
||||
if (!remainder) return { matched: true, command: { action: "focus" } };
|
||||
const [subcommand, ...extra] = remainder.split(/\s+/);
|
||||
if (["edit", "pause", "resume", "clear"].includes(subcommand!)) {
|
||||
if (extra.length > 0) {
|
||||
return { matched: true, error: `/goal ${subcommand} does not accept extra arguments.` };
|
||||
}
|
||||
return { matched: true, command: { action: subcommand as "edit" | "pause" | "resume" | "clear" } };
|
||||
}
|
||||
return { matched: true, command: { action: "create", objective: remainder } };
|
||||
}
|
||||
Reference in new issue
Block a user