From 18aa2b353daa65058fa26eb05875c9cd98072a82 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:33:09 -0600 Subject: [PATCH] feat(antigravity): /plan selects Plan mode and keeps Antigravity read-only while planning (#22727) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 `, 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 ` 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 ?` 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 --- .../drivers/acpx/acpx-runtime-adapter.test.ts | 56 ++++++++ .../src/drivers/acpx/acpx-runtime-adapter.ts | 7 + .../acpx/antigravity-plan-mode.test.ts | 54 ++++++++ .../src/drivers/acpx/antigravity-plan-mode.ts | 51 +++++++ .../src/drivers/acpx/runtime-host.test.ts | 32 +++++ .../src/drivers/acpx/runtime-host.ts | 7 + .../src/drivers/runner-tool-bridge.ts | 4 + packages/shared/src/index.ts | 1 + .../shared/src/leading-user-command.test.ts | 60 +++++++++ packages/shared/src/leading-user-command.ts | 35 +++++ .../runner-e2e/source-sdk-public-inputs.json | 4 +- .../task-chat/TaskChatComposer.test.tsx | 125 +++++++++++++++++- .../components/task-chat/TaskChatComposer.tsx | 110 ++++++--------- .../components/task-chat/composer-commands.ts | 90 +++++++++++++ 14 files changed, 566 insertions(+), 70 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.ts create mode 100644 packages/shared/src/leading-user-command.test.ts create mode 100644 packages/shared/src/leading-user-command.ts create mode 100644 ui/src/components/task-chat/composer-commands.ts diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts index abf969e42d7..a51cac0bca5 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts @@ -271,6 +271,62 @@ describe("Codex ACPX runtime adapter", () => { await port.close({ reason: "test finished" }); }); + it.each([true, false])("keeps an Antigravity Plan-mode run read-only at the permission boundary (readOnly=%s)", async readOnly => { + const pending = pendingExtensionTurn("plan-turn"); + const runtime = fakeRuntime(); + vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); + const command = fakeCommand(); + vi.mocked(command.spawn).mockReturnValue(fakeChild()); + let exit!: () => void; + const providerExit = new Promise(resolve => { exit = resolve; }); + let created!: AcpRuntimeOptions; + const options = openOptions(command); + options.profile = resolveQualifiedAcpxProfile("antigravity", "gemini-3.8-flash-low"); + options.permissionMode = "approve-all"; + options.readOnly = readOnly; + options.mcpServers = [{ name: "paperclip", url: "http://127.0.0.1:3212/mcp", bearerToken: "bridge-fixture", runnerOwned: true }, + { name: "runner_extra", url: "http://127.0.0.1:3213/mcp", bearerToken: "extra-fixture", runnerOwned: true }]; + options.paperclipTools = ["write_document"]; + vi.mocked(runtime.ensureSession).mockImplementationOnce(async () => { + created.spawnAgent?.({ command: "ignored", args: [], options: {} }); + const guard = created.protocolGuardFactory!(); + guard("outbound", { id: 0, method: "initialize", params: {} }); + guard("inbound", { id: 0, result: { agentInfo: { name: "antigravity-acp", version: "1.5.2" }, + agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } } }); + const open = { id: 1, method: "session/new", params: { cwd: "/workspace" } as Record }; + guard("outbound", open); + const admission = open.params._meta.antigravity.paperclipAdmission; + guard("inbound", { id: 1, result: { sessionId: "backend-1", modes: { currentModeId: "default" }, + _meta: { paperclipAntigravityAdmission: { ...admission, sessionId: "backend-1", connectionId: "owned-connection" } } } }); + return HANDLE; + }); + const port = await openQualifiedAcpxRuntime(options, { + createRegistry: () => registry(), createStore: () => store(), + awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, + createRuntime: value => { created = value; return runtime; }, + }); + const turn = port.startTurn({ text: "Plan it", requestId: "plan-turn", onPermissionRequest: vi.fn() }); + await turn.promptStarted; + const ask = (toolCall: Record) => created.onPermissionRequest!({ sessionId: "backend-1", + raw: { sessionId: "backend-1", toolCall }, inferredKind: "other" } as never, { signal: new AbortController().signal }); + const write = { toolCallId: "w", title: "Run write_to_file?", kind: "edit", rawInput: { TargetFile: "/workspace/greeting.txt" } }; + const command_ = { toolCallId: "c", title: "touch greeting.txt", kind: "execute", rawInput: { CommandLine: "touch greeting.txt" } }; + const paperclip = { toolCallId: "p", title: "paperclip_write_document", kind: "other", rawInput: {}, + _meta: { mcp: { tool: "write_document", server: "paperclip" }, is_mcp_tool_call: true } }; + const refused = readOnly ? "reject_once" : "allow_once"; + await expect(ask(write)).resolves.toEqual({ outcome: refused }); + await expect(ask(command_)).resolves.toEqual({ outcome: refused }); + // Paperclip's own tools stay governed by Paperclip's Plan-mode rules. + await expect(ask(paperclip)).resolves.toEqual({ outcome: "allow_once" }); + // Another runner-owned server is not Paperclip's bridge. + await expect(ask({ ...paperclip, title: "runner_extra_write_file", + _meta: { mcp: { tool: "write_file", server: "runner_extra" }, is_mcp_tool_call: true } })).resolves.toEqual({ outcome: refused }); + pending.settle(); + await turn.result; + exit(); + await port.close({ reason: "test finished" }); + }); + it("recognises only a switch_mode request that carries plan text as a Claude plan proposal", () => { expect(claudeExitPlanModeProposal({ raw: { toolCall: { toolCallId: "t1", kind: "switch_mode", rawInput: { plan: " # P " } } } })) .toEqual({ toolCallId: "t1", markdown: "# P" }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts index 39923380a86..4f4cd78dffd 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts @@ -52,6 +52,7 @@ import { AcpxApprovalRequiredError, decideAcpxPermission } from "./permission-po import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js"; import { createCursorInstructionAdmission } from "./cursor-instructions.js"; import { antigravitySavedStateIncompatible, createAntigravityAdmission } from "./antigravity-admission.js"; +import { ANTIGRAVITY_PAPERCLIP_MCP_SERVER, antigravityPlanModeAllows } from "./antigravity-plan-mode.js"; import { createAcpxModeBinding } from "./provider-mode.js"; import { isAcpPromptRequest, type AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js"; import { assertCopilotPromptPolicy, createCopilotPolicyEnforcement, type CopilotPolicyEnforcement } from "./copilot-policy.js"; @@ -358,6 +359,10 @@ export async function openQualifiedAcpxRuntime( .filter((server) => server.runnerOwned) .map((server) => server.name), ); + const antigravityPlanPolicy = { + paperclipServerOwned: options.mcpServers.some(server => server.runnerOwned && server.name === ANTIGRAVITY_PAPERCLIP_MCP_SERVER), + paperclipTools: new Set(options.paperclipTools ?? []), + }; const permissionBoundary: { active: AbortController | null; hasAdmittedTurn: boolean; @@ -561,6 +566,8 @@ export async function openQualifiedAcpxRuntime( } if (options.profile.agent === "kimi" && options.readOnly === true && !kimiReadOnlyPermissionAllowed(request, runnerOwnedMcpServerNames)) return { outcome: "reject_once" }; + if (options.profile.agent === "antigravity" && options.readOnly === true + && !antigravityPlanModeAllows(request, antigravityPlanPolicy)) return { outcome: "reject_once" }; const disposition = decideAcpxPermission( options.profile.agent, options.permissionMode, diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.test.ts new file mode 100644 index 00000000000..6e36e33ff01 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { antigravityPlanModeAllows } from "./antigravity-plan-mode.js"; + +// The runner-owned Paperclip bridge and the tools it registered for this run. +const policy = { paperclipServerOwned: true, paperclipTools: new Set(["read_agent_instructions", "write_document", "paperclip_finish"]) }; +// The 1.5.2 server's session/request_permission toolCall shapes (server.py +// _permission_handler; tools.py infer_tool_kind / unwrap_mcp_tool_call). +const request = (toolCall: unknown) => ({ raw: { sessionId: "native-session", toolCall } }); +const mcp = (server: string, tool: string, kind = "other") => + ({ toolCallId: "m", title: `${server}_${tool}`, kind, rawInput: {}, _meta: { mcp: { tool, server }, is_mcp_tool_call: true } }); + +describe("Antigravity plan mode permissions", () => { + it.each([ + ["a file write", { toolCallId: "w", title: "Run write_to_file?", kind: "edit", rawInput: { TargetFile: "/workspace/greeting.txt", CodeContent: "hello" } }], + ["a file edit", { toolCallId: "e", title: "Run replace_file_content?", kind: "edit", rawInput: { TargetFile: "/workspace/a.ts" } }], + ["a write tool that reports itself as a read", { toolCallId: "w2", title: "Run write_to_file?", kind: "read", rawInput: {} }], + ["a read tool name with a mismatched kind", { toolCallId: "r2", title: "Run view_file?", kind: "edit", rawInput: {} }], + ["a terminal command", { toolCallId: "c", title: "ls -la", kind: "execute", rawInput: { CommandLine: "ls -la" } }], + ["a terminal command that reports itself as a read", { toolCallId: "c2", title: "cat a.txt", kind: "read", rawInput: { CommandLine: "cat a.txt" } }], + ["an unknown tool that reports itself as a read", { toolCallId: "u", title: "Run mystery_tool?", kind: "read", rawInput: {} }], + ["an unclassified tool", { toolCallId: "o", title: "Run generate_image?", kind: "other", rawInput: {} }], + ["a tool without a kind", { toolCallId: "n", title: "Run view_file?", rawInput: {} }], + ["another MCP server's tool", mcp("github", "create_issue")], + ["another MCP server's tool that claims to read", mcp("github", "read", "read")], + ["a non-Paperclip server's tool with a Paperclip tool name", mcp("runner_extra", "write_document")], + ["a Paperclip-server tool the bridge did not register", mcp("paperclip", "delete_company")], + ["an MCP tool that names no server", { toolCallId: "m2", title: "create_issue", kind: "other", rawInput: {}, _meta: { mcp: { tool: "create_issue" }, is_mcp_tool_call: true } }], + ["a read title on an MCP call", { ...mcp("github", "view_file", "read"), title: "Run view_file?" }], + ])("refuses %s", (_name, toolCall) => { + expect(antigravityPlanModeAllows(request(toolCall), policy)).toBe(false); + }); + + it.each([ + ["a file read", { toolCallId: "r", title: "Run view_file?", kind: "read", rawInput: { AbsolutePath: "/workspace/a.ts" } }], + ["a search", { toolCallId: "s", title: "Run grep_search?", kind: "search", rawInput: { Query: "x" } }], + ["a directory listing", { toolCallId: "l", title: "Run list_dir?", kind: "search", rawInput: {} }], + ["a page read", { toolCallId: "f", title: "Run read_url_content?", kind: "fetch", rawInput: { Url: "https://example.com" } }], + ["a registered Paperclip tool", mcp("paperclip", "write_document")], + ["a registered Paperclip tool with a prefixed name", mcp("paperclip", "paperclip_read_agent_instructions")], + ["Paperclip's finish tool", mcp("paperclip", "paperclip_finish")], + ])("keeps %s available", (_name, toolCall) => { + expect(antigravityPlanModeAllows(request(toolCall), policy)).toBe(true); + }); + + it("refuses Paperclip tools when the run's paperclip server is not runner-owned", () => { + expect(antigravityPlanModeAllows(request(mcp("paperclip", "write_document")), { ...policy, paperclipServerOwned: false })).toBe(false); + }); + + it("refuses malformed requests", () => { + expect(antigravityPlanModeAllows({}, policy)).toBe(false); + expect(antigravityPlanModeAllows(request(null), policy)).toBe(false); + expect(antigravityPlanModeAllows(request([]), policy)).toBe(false); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.ts new file mode 100644 index 00000000000..8e50bc79abd --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-plan-mode.ts @@ -0,0 +1,51 @@ +import { canonicalRunnerToolName } from "../runner-tool-bridge.js"; + +/** Antigravity 1.5.2 has no plan session mode (only default, auto_edit and + * yolo), and its native `/plan` command does not reach the harness intact: the + * pinned SDK hands the harness the command name as + * "BuiltinSlashCommandName.PLAN", which the harness shows the model as text and + * never treats as planning mode (observed live on 1.5.2). Paperclip's Plan mode + * therefore keeps the run read-only here, at the provider's permission prompt. + * + * Allowed, and nothing else (fail closed): + * - the 1.5.2 server's built-in research tools, named by the exact + * `Run ?` title its permission prompt uses for non-MCP tools, when the + * reported kind also matches that tool's kind (tools.py infer_tool_kind); + * - tools the runner's own Paperclip bridge registered for this run, on the + * runner-owned server named `paperclip`. The Paperclip server applies its + * Plan-mode rules to these, and the plan document is written through them. + * The provider's kind alone never grants a read, and no other MCP server is + * trusted, runner-owned or not. */ +export const ANTIGRAVITY_PAPERCLIP_MCP_SERVER = "paperclip"; + +const RESEARCH_TOOL_KINDS: ReadonlyMap = new Map([ + ["view_file", "read"], ["read_file", "read"], ["client_view_file", "read"], + ["grep_search", "search"], ["find_by_name", "search"], ["list_dir", "search"], + ["search_directory", "search"], ["list_directory", "search"], ["find_file", "search"], + ["search_web", "search"], ["read_url_content", "fetch"], +]); + +export interface AntigravityPlanModePolicy { + /** The run's `paperclip` MCP server is the runner-owned Paperclip bridge. */ + paperclipServerOwned: boolean; + /** Canonical names of the tools that bridge registered for this run. */ + paperclipTools: ReadonlySet; +} + +export function antigravityPlanModeAllows(request: { raw?: unknown }, policy: AntigravityPlanModePolicy): boolean { + const toolCall = record(record(request.raw).toolCall); + const meta = record(toolCall._meta); + // Any metadata bag sends the call down the strict MCP path. + if (toolCall._meta !== undefined && toolCall._meta !== null) { + const mcp = record(meta.mcp); + return meta.is_mcp_tool_call === true && policy.paperclipServerOwned + && mcp.server === ANTIGRAVITY_PAPERCLIP_MCP_SERVER && typeof mcp.tool === "string" + && policy.paperclipTools.has(canonicalRunnerToolName(mcp.tool)); + } + const name = typeof toolCall.title === "string" ? /^Run ([a-z_]+)\?$/.exec(toolCall.title)?.[1] : undefined; + return name !== undefined && RESEARCH_TOOL_KINDS.get(name) === toolCall.kind; +} + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts index 26331441036..55b48566eb6 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts @@ -10,6 +10,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { ANTIGRAVITY_PAPERCLIP_MCP_SERVER, antigravityPlanModeAllows } from "./antigravity-plan-mode.js"; +import { canonicalRunnerToolName } from "../runner-tool-bridge.js"; import { NATIVE_RUNTIME_ASSET_SCHEMA, @@ -1111,6 +1113,36 @@ describe("ACPX runtime host", () => { } finally { await host.close({ reason: "tool preload verified" }); } }); + it("gives the Antigravity Plan-mode gate the bridge's served catalog, finish and block included", async () => { + const fixture = await hostFixture(); + let opened: AcpxRuntimePortOpenOptions | undefined; + const host = await AcpxRuntimeHost.open({ + ...fixture.options, agent: "codex", model: "gpt-5.6-sol", permissionMode: "deny-all", + environment: { PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET: "{}" }, + semanticTools: { tools: [{ name: "write_document", inputSchema: { type: "object", properties: {} } }], + privateTools: [{ name: "report_private_progress", inputSchema: { type: "object", properties: {} } }], handler: async () => ({}) }, + }, fixture.dependencies({ openRuntime: async options => { opened = options; return runtimePort(); } })); + try { + const bridge = urlBridge(opened!.mcpServers.find(server => server.runnerOwned)!); + const response = await fetch(bridge.url, { method: "POST", headers: { Authorization: `Bearer ${bridge.bearerToken}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }) }); + const served = ((await response.json()) as { result: { tools: Array<{ name: string }> } }).result.tools.map(tool => tool.name); + expect(served).toEqual(expect.arrayContaining(["paperclip_finish", "paperclip_block"])); + // Production derives the policy from the bridge's admitted names: the + // served catalog plus private tools, finish and block included. + expect([...opened!.paperclipTools!].sort()).toEqual([...served, "report_private_progress"].map(canonicalRunnerToolName).sort()); + const policy = { paperclipServerOwned: bridge.name === ANTIGRAVITY_PAPERCLIP_MCP_SERVER, paperclipTools: new Set(opened!.paperclipTools) }; + const call = (tool: string, server = bridge.name) => ({ raw: { toolCall: { title: `${server}_${tool}`, kind: "other", + _meta: { mcp: { tool, server }, is_mcp_tool_call: true } } } }); + expect(antigravityPlanModeAllows(call("paperclip_finish"), policy)).toBe(true); + expect(antigravityPlanModeAllows(call("paperclip_block"), policy)).toBe(true); + expect(antigravityPlanModeAllows(call("write_document"), policy)).toBe(true); + expect(antigravityPlanModeAllows(call("report_private_progress"), policy)).toBe(true); + expect(antigravityPlanModeAllows(call("delete_company"), policy)).toBe(false); + expect(antigravityPlanModeAllows({ raw: { toolCall: { title: "Run write_to_file?", kind: "edit" } } }, policy)).toBe(false); + } finally { await host.close({ reason: "plan catalog verified" }); } + }); + it("forwards semantic receipt capture through the real runtime host and authenticated bridge", async () => { const fixture = await hostFixture(); const events: CanonicalProviderEvent[] = []; diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index f0d30eb474f..5aeb084ecd9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -36,6 +36,7 @@ import { releaseMaterializedNativeRuntimeSkills, } from "../runtime-context-materializer.js"; import { + canonicalRunnerToolName, startRunnerToolBridge, type RunnerToolBridge, type RunnerToolBridgeOptions, @@ -224,6 +225,8 @@ export interface AcpxRuntimePortOpenOptions { /** Abort provider admission and clean any runtime that resolves too late. */ signal?: AbortSignal; mcpServers: readonly AcpxMcpServerBinding[]; + /** Canonical names of the tools the runner-owned Paperclip bridge registered. */ + paperclipTools?: readonly string[]; onGoalUpdate?: (goal: AcpxRuntimeGoalSnapshot | null) => void; /** * Transfer the provider cleanup proof before a failed open settles. The host @@ -723,6 +726,10 @@ export class AcpxRuntimeHost { ...(toolBridge ? [{ name: preconfigured ? `paperclip_runner_${binding.profileSessionKey.slice(-16)}` : "paperclip", url: toolBridge.url, bearerToken: toolBridge.secret, runnerOwned: true }] : []), ], + // The bridge's own admitted names, one source: the run's tools, + // the reserved finish and block tools it adds itself, and any + // private tools. + ...(toolBridge ? { paperclipTools: toolBridge.admittedToolNames.map(canonicalRunnerToolName) } : {}), ...(options.onGoalUpdate === undefined ? {} : { onGoalUpdate: options.onGoalUpdate }), diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts index 7ccabc60adc..5d543a5f925 100644 --- a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts @@ -72,6 +72,9 @@ export interface RunnerToolBridgeOptions { export interface RunnerToolBridge { readonly url: string; readonly secret: string; + /** Every tool name this bridge admits: the served catalog, its reserved + * finish and block tools, and any private tools. */ + readonly admittedToolNames: readonly string[]; close(): Promise; } @@ -243,6 +246,7 @@ export async function startRunnerToolBridge( return Object.freeze({ url: typeof address === "string" ? "http://localhost/mcp" : `http://127.0.0.1:${address.port}/mcp`, secret, + admittedToolNames: Object.freeze(admittedTools.map((tool) => tool.name)), async close() { if (closed) return; closed = true; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 3fa6eb48ed1..7802ff6e3af 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3150,3 +3150,4 @@ export * from "./tool-call-progress.js"; export * from "./mcp-skills.js"; export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscale.js"; export * from "./agent-setup-progress.js"; +export { parseLeadingUserCommand, type LeadingUserCommand } from "./leading-user-command.js"; diff --git a/packages/shared/src/leading-user-command.test.ts b/packages/shared/src/leading-user-command.test.ts new file mode 100644 index 00000000000..3990464c95e --- /dev/null +++ b/packages/shared/src/leading-user-command.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; +import { parseLeadingUserCommand } from "./leading-user-command.js"; + +const plan = ["plan"] as const; + +describe("parseLeadingUserCommand", () => { + it("reads a leading allowlisted command and its argument text", () => { + expect(parseLeadingUserCommand("/plan Add a greeting file", plan)).toEqual({ command: "plan", argument: "Add a greeting file" }); + expect(parseLeadingUserCommand("/plan", plan)).toEqual({ command: "plan", argument: "" }); + expect(parseLeadingUserCommand("/plan\n\nLine one\nLine two ", plan)).toEqual({ command: "plan", argument: "Line one\nLine two" }); + }); + + it("allows leading whitespace and newlines", () => { + expect(parseLeadingUserCommand(" \n\t/plan go", plan)).toEqual({ command: "plan", argument: "go" }); + }); + + it("uses the native server's whitespace, not JavaScript's", () => { + // Python str patterns treat U+001C-U+001F as whitespace; JavaScript \s does not. + expect(parseLeadingUserCommand("\u001c/plan\u001fgo", plan)).toEqual({ command: "plan", argument: "go" }); + expect(parseLeadingUserCommand(" /plan go", plan)).toEqual({ command: "plan", argument: "go" }); + // JavaScript \s includes U+FEFF; Python does not, so it is not a separator. + expect(parseLeadingUserCommand("/plan go", plan)).toBeNull(); + expect(parseLeadingUserCommand("/plango", plan)).toBeNull(); + }); + + it("ignores a command that is not at the start", () => { + expect(parseLeadingUserCommand("Please /plan this first", plan)).toBeNull(); + expect(parseLeadingUserCommand("Context\n/plan this", plan)).toBeNull(); + }); + + it("ignores quoted, pasted, forwarded or wrapped content", () => { + expect(parseLeadingUserCommand("> /plan from a quoted reply", plan)).toBeNull(); + expect(parseLeadingUserCommand("```\n/plan\n```", plan)).toBeNull(); + expect(parseLeadingUserCommand("`/plan` is a command", plan)).toBeNull(); + expect(parseLeadingUserCommand("---------- Forwarded message ----------\n/plan x", plan)).toBeNull(); + expect(parseLeadingUserCommand("/plan x", plan)).toBeNull(); + expect(parseLeadingUserCommand("\\/plan ordinary text", plan)).toBeNull(); + expect(parseLeadingUserCommand("⁠/plan neutralised", plan)).toBeNull(); + }); + + it("matches the exact lower-case name only", () => { + expect(parseLeadingUserCommand("/PLAN x", plan)).toBeNull(); + expect(parseLeadingUserCommand("/Plan x", plan)).toBeNull(); + expect(parseLeadingUserCommand("/planning notes", plan)).toBeNull(); + expect(parseLeadingUserCommand("/plans", plan)).toBeNull(); + }); + + it("does not read a path or URL as a command", () => { + expect(parseLeadingUserCommand("/plan/2026/notes.md", plan)).toBeNull(); + expect(parseLeadingUserCommand("/plan?draft=1", plan)).toBeNull(); + expect(parseLeadingUserCommand("https://example.com/plan x", plan)).toBeNull(); + }); + + it("accepts only allowlisted commands", () => { + expect(parseLeadingUserCommand("/swarm build it", plan)).toBeNull(); + expect(parseLeadingUserCommand("/logout", plan)).toBeNull(); + expect(parseLeadingUserCommand("/swarm build it", ["plan", "swarm"])).toEqual({ command: "swarm", argument: "build it" }); + expect(parseLeadingUserCommand("/plan x", [])).toBeNull(); + }); +}); diff --git a/packages/shared/src/leading-user-command.ts b/packages/shared/src/leading-user-command.ts new file mode 100644 index 00000000000..996eea6d3ab --- /dev/null +++ b/packages/shared/src/leading-user-command.ts @@ -0,0 +1,35 @@ +/** + * The one rule for reading a slash command as a real user request. + * + * Source of trust: the caller passes only text the signed-in user typed and + * submitted themselves in Paperclip's task composer (a comment body, or the + * body of a new task). Never pass agent-authored text, chat or connector + * messages, API-posted text, issue descriptions written by someone else, or + * any prompt Paperclip assembles for an agent. Those stay ordinary text, and + * harness guards (for example Antigravity's native-command neutraliser) keep + * them from acting as commands. + * + * Within that text, only a command at the very start counts: optional + * whitespace, then `/name`, then whitespace or the end. The name is exact and + * lower-case, and must be in the caller's allowlist. Whitespace follows the + * Python rules the Antigravity server uses (U+001C-U+001F count, U+FEFF does + * not), so this never accepts a command boundary the server would not. + */ +export interface LeadingUserCommand { + command: Name; + /** The rest of the message, trimmed. Empty when only the command was sent. */ + argument: string; +} + +const WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000"; +const LEADING = new RegExp(`^[${WHITESPACE}]*\\/([a-z]+)(?=[${WHITESPACE}]|$)`); +const TRIM = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, "g"); + +export function parseLeadingUserCommand( + userAuthoredText: string, + allowlist: readonly Name[], +): LeadingUserCommand | null { + const match = LEADING.exec(userAuthoredText); + if (!match || !(allowlist as readonly string[]).includes(match[1]!)) return null; + return { command: match[1] as Name, argument: userAuthoredText.slice(match[0].length).replace(TRIM, "") }; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 9ed0c718053..908316dc65d 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -278,7 +278,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "3fa6eb48ed1e6ccf989a35e1449da40f1975bf05", + "packages/shared/src/index.ts": "7802ff6e3afa7d95eabeba96f58d655649c6ff16", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -291,6 +291,8 @@ "packages/shared/src/issue-thread-interactions.test.ts": "6f516055744fcedd2e0c06ce82c6a1a019120762", "packages/shared/src/issue-write-denial.test.ts": "e21b93aa79e6635c019ac338eff954ec618a98ed", "packages/shared/src/issue-write-denial.ts": "e6b4d72a83f6e4e76e85e34a80f88d1d69b7dfe4", + "packages/shared/src/leading-user-command.test.ts": "3990464c95e6f7e1de078b817f3a296a50e53f78", + "packages/shared/src/leading-user-command.ts": "996eea6d3ab1088462f690a37b113c6ace29583f", "packages/shared/src/link-preview.test.ts": "136041c928343ad6272f43701b39cf95be255f3e", "packages/shared/src/link-preview.ts": "b7431d4c30a12067e80e6806728b3ae7c7541f8f", "packages/shared/src/markdown-work-products.test.ts": "7293d14ad45ec2b11b5deaab4ce070c36f7c9010", diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx index 842d8a9d129..3f7439548f0 100644 --- a/ui/src/components/task-chat/TaskChatComposer.test.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx @@ -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]()")).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( + '[data-testid="mention-autocomplete-menu"] button[type="button"]')).some(node => node.textContent?.includes("/plan")); + render(); + typeText("/pl"); + await placeCaretAtEnd(); + expect(planOffered()).toBe(true); + render(); + 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(); + pressKey("Enter", { metaKey: true }); + await flushAsync(); + expect(creation.onSubmit).toHaveBeenCalledWith("", "planning", null); + const onWorkModeChange = vi.fn(); + const bare = { ...creation, onSubmit: vi.fn() }; + render(); + 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(); + 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(); + 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, diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index 972ebd4f009..014c53f23dc 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -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; } -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" diff --git a/ui/src/components/task-chat/composer-commands.ts b/ui/src/components/task-chat/composer-commands.ts new file mode 100644 index 00000000000..0509c7513c4 --- /dev/null +++ b/ui/src/components/task-chat/composer-commands.ts @@ -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 ` 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 } }; +}