diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts index 41333920785..6d9d0dcc96f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from "vitest"; +import { providerFailureFromError } from "../provider-failure.js"; +import { AntigravitySwarmError } from "./antigravity-swarm-guard.js"; import { antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard, } from "./antigravity-swarm-guard.js"; @@ -122,4 +124,12 @@ describe("Antigravity CLI swarm guard (replaces the registry admission receipt)" .toMatchObject({ kind: "rate_limit", httpStatus: 429 }); expect(classifyAntigravityRefusalText("Both files are written.")).toBeNull(); }); + + it("carries its plain message to the user as a typed provider failure", () => { + const error = new AntigravitySwarmError("ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED", "The Antigravity CLI on this computer is not signed in to Google."); + expect(providerFailureFromError(new Error("session.open failed", { cause: error }))).toMatchObject({ + provider: "antigravity", phase: "startup", category: "authentication", + message: "The Antigravity CLI on this computer is not signed in to Google.", providerCode: "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED", + }); + }); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts index a0c980ff9c8..b5a5c2004c9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts @@ -1,4 +1,6 @@ import { createHash } from "node:crypto"; +import type { ProviderFailure } from "../../contracts/provider-failure.generated.js"; +import { createProviderFailure } from "../provider-failure.js"; import { ANTIGRAVITY_CLI_DISTRIBUTION } from "./antigravity-cli-pins.js"; /** @@ -34,9 +36,13 @@ export type AntigravitySwarmErrorCode = /** `message` is written for the person who asked for the swarm. */ export class AntigravitySwarmError extends Error { readonly retryable = false; + /** Lets the sidecar hand this plain message to the user instead of a generic open failure. */ + readonly providerFailure: ProviderFailure | null; constructor(readonly code: AntigravitySwarmErrorCode, message: string) { super(message); this.name = "AntigravitySwarmError"; + this.providerFailure = createProviderFailure({ provider: "antigravity", phase: "startup", message, providerCode: code, + category: code === "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED" ? "authentication" : code === "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT" ? "timeout" : "unknown" }); } } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts index 9eda89e016c..dfc504e4533 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { PRP_BLOCK_TOOL_NAME, PRP_COMPLETION_TOOL_NAME } from "../../contracts/completion-result.js"; import { antigravityRouteChangeRefusal, antigravitySwarmTools, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; import { createAcpxModeBinding, resolveAcpxProviderMode } from "./provider-mode.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; @@ -43,10 +44,14 @@ describe("Antigravity swarm route selection", () => { expect(antigravitySwarmLaunchEnvironment({ HOME: "/private/home" }, { agentHomeDirectory: "/private", platform: "darwin", realHome: "/Users/owner" }).HOME).toBe("/Users/owner"); }); - it("keeps Paperclip delegation tools out of a swarm turn", () => { - const tools = ["paperclip_finish_task", "paperclip_block_task", "paperclip_create_task", "paperclip_create_issue", "paperclip_hire_agent", - "paperclip_read_task", "paperclip_call_assigned_tool", "paperclip_search_assigned_tools"].map(name => ({ name })); - expect(antigravitySwarmTools(tools).map(tool => tool.name)).toEqual(["paperclip_finish_task", "paperclip_block_task", "paperclip_read_task", "paperclip_call_assigned_tool", "paperclip_search_assigned_tools"]); + it("keeps every Paperclip operation that creates or hands off work out of a swarm turn, as the production catalog names them", () => { + const delegating = ["create_task", "reassign_task", "set_dependencies", "hire_agent", "call_api", "create_project", "create_case", "update_case", + "handoff_case", "create_workflow", "update_workflow", "update_routine", "create_area", "create_responsibility"]; + const kept = [PRP_COMPLETION_TOOL_NAME, PRP_BLOCK_TOOL_NAME, "get_task_context", "read_document", "write_document", "report_progress", "search_tasks", "list_agents"]; + // Production descriptors carry the bare operation id as name (sidecar_run_tool_operations). + const catalog = [...delegating, ...kept].map(name => ({ name, operationId: name, description: "x" })); + expect(antigravitySwarmTools(catalog).map(tool => tool.name)).toEqual(kept); + expect(antigravitySwarmTools([{ name: "paperclip_create_task" }, { name: "x", operationId: "hire_agent" }])).toEqual([]); }); it("lets the server open a fresh conversation when a saved one belongs to the other route", () => { diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts index 1eb8f4cf2b1..85d8cd813f4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts @@ -1,8 +1,9 @@ import { userInfo } from "node:os"; import { join } from "node:path"; +import { canonicalRunnerToolName } from "../runner-tool-bridge.js"; import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js"; import { ANTIGRAVITY_CLI_DISTRIBUTION } from "./antigravity-cli-pins.js"; -import { resolveAntigravityCliLaunch, type AntigravityCliLaunchOptions } from "./antigravity-cli-installation.js"; +import { AntigravityCliRuntimeError, resolveAntigravityCliLaunch, type AntigravityCliLaunchOptions } from "./antigravity-cli-installation.js"; import { ANTIGRAVITY_CLI_STABLE_ENDPOINT, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError } from "./antigravity-swarm-guard.js"; import type { VerifiedAcpxInstallation } from "./installation-integrity.js"; @@ -45,7 +46,11 @@ export async function verifyAntigravitySwarmInstallation( stateDirectory: () => string, options: Omit = {}, ): Promise { - const pinned = await resolveAntigravityCliLaunch(options); + const pinned = await resolveAntigravityCliLaunch(options).catch((error: unknown) => { + // The runtime-missing and unsupported-platform messages are written for people; keep them visible. + if (error instanceof AntigravityCliRuntimeError) throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", `Swarm is not available on this computer: ${error.message}`); + throw error; + }); return Object.freeze({ commandDigest: pinned.commandDigest, agentServerPackageJsonPath: null, @@ -74,12 +79,23 @@ export function antigravitySwarmLaunchEnvironment( return { ...environment, ...ANTIGRAVITY_CLI_DISTRIBUTION.environment }; } -/** Paperclip tools that create tasks, assign work or hire. A swarm is one run with one assignee. */ -const DELEGATION_TOOL = /^paperclip_(?:create_(?:task|issue|subtask|agent)|hire|delegate|assign|reassign)/; +/** + * Paperclip operations that create, assign or hand off work, hire, or reach the + * generic API (which can do any of those). A swarm is one run with one + * assignee, so none of them is offered on a swarm turn. Production catalogs + * name tools by bare operation id; prefixed names are matched canonically. + */ +export const ANTIGRAVITY_SWARM_DELEGATING_OPERATIONS: ReadonlySet = new Set([ + "create_task", "create_issue", "create_subtask", "reassign_task", "assign_task", "set_dependencies", "delegate_task", + "hire_agent", "create_agent", "call_api", + "create_project", "create_case", "update_case", "handoff_case", "create_workflow", "update_workflow", + "update_routine", "create_routine", "create_area", "update_area", "create_responsibility", "update_responsibility", +]); /** The bridge catalog for a swarm turn: the run's tools without delegation. */ export function antigravitySwarmTools>>(tools: readonly T[]): T[] { - return tools.filter(tool => !(typeof tool.name === "string" && DELEGATION_TOOL.test(tool.name))); + return tools.filter(tool => ![tool.name, tool.operationId].some(name => + typeof name === "string" && ANTIGRAVITY_SWARM_DELEGATING_OPERATIONS.has(canonicalRunnerToolName(name)))); } /** diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.ts index cf478f59cf8..d49ac40217e 100644 --- a/packages/shared/src/feature-catalog.ts +++ b/packages/shared/src/feature-catalog.ts @@ -412,7 +412,7 @@ export const INSTANCE_FEATURE_CATALOG: Record { .post("/api/issues/11111111-1111-4111-8111-111111111111/comments") .send({ body: "two helpers write a.txt and b.txt", nativeCommand: "swarm" }); expect(res.status).toBe(201); - expect(mockSwarm.record).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ commentId: "comment-1", userId: "local-board" })); + // Written in the same transaction as the comment, so neither can exist without the other. + expect(mockSwarm.record).toHaveBeenCalledWith(mockTx, expect.objectContaining({ commentId: "comment-1", userId: "local-board" })); + expect(mockIssueService.addComment).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.anything(), expect.anything(), mockTx); await waitForWakeup(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith( "22222222-2222-4222-8222-222222222222", expect.objectContaining({ contextSnapshot: expect.objectContaining({ antigravitySwarmCommentId: "comment-1" }) }), diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index c30ab4714ee..895cf3ce7f4 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -19816,6 +19816,12 @@ export function issueRoutes( }, tx, ); + // The swarm request commits with its comment or not at all. + if (swarmRequested && actor.actorType === "user") { + await recordAntigravitySwarmRequest(tx as unknown as Db, { + companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: insertedComment.id, userId: actor.actorId, + }); + } const updated = actor.actorType === "user" && currentIssue.status !== "done" ? await svc.update( @@ -19921,9 +19927,15 @@ export function issueRoutes( dbOrTx, ); const needsFastResponse = actor.actorType === "user" && currentIssue.assigneeAgentId && !["done", "cancelled", "backlog"].includes(currentIssue.status); - comment = needsFastResponse ? await db.transaction(async tx => { + comment = needsFastResponse || swarmRequested ? await db.transaction(async tx => { const saved = await add(tx as unknown as Db); - if (actor.actorType === "user" && currentIssue.assigneeAgentId && !["done", "cancelled", "backlog"].includes(currentIssue.status)) { + // The swarm request commits with its comment or not at all. + if (swarmRequested && actor.actorType === "user") { + await recordAntigravitySwarmRequest(tx as unknown as Db, { + companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: saved.id, userId: actor.actorId, + }); + } + if (needsFastResponse && actor.actorType === "user" && currentIssue.assigneeAgentId && !["done", "cancelled", "backlog"].includes(currentIssue.status)) { await enqueueFastResponse(tx as unknown as Db, { companyId: currentIssue.companyId, issueId: currentIssue.id, agentId: currentIssue.assigneeAgentId, responsibleUserId: actor.actorId, sourceCommentId: saved.id, sourceKey: `comment:${saved.id}`, acceptedAt: new Date(saved.createdAt) }); fastResponseEnqueued = true; @@ -20060,11 +20072,6 @@ export function issueRoutes( comment, currentIssue.assigneeAgentId, ); - if (swarmRequested && req.actor.type === "board" && req.actor.userId) { - await recordAntigravitySwarmRequest(db, { - companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: comment.id, userId: req.actor.userId, - }); - } const swarmWakeContext = swarmRequested ? { antigravitySwarmCommentId: comment.id } : {}; await revalidateActiveSourceRecoveryAfterCommittedWrite({ diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts new file mode 100644 index 00000000000..f2080171fa2 --- /dev/null +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -0,0 +1,98 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { activityLog, agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { ANTIGRAVITY_SWARM_REQUESTED_ACTION, recordAntigravitySwarmRequest, resolveAntigravitySwarmRun } from "./antigravity-swarm.js"; +import { instanceSettingsService } from "./instance-settings.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const USER = "swarm-user"; + +describe.skipIf(!support.supported)("trusted /swarm run selection (database)", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-antigravity-swarm-"); + db = createDb(database.connectionString); + await instanceSettingsService(db).updateExperimental({ enableAntigravitySwarm: true }); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function seed(options: { author?: "user" | "agent"; record?: "match" | "none" | "other-actor" | "other-comment" } = {}) { + const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: `S${randomUUID().slice(0, 4)}` }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning(); + const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Swarm", status: "todo", assigneeAgentId: agent!.id }).returning(); + const [comment] = await db.insert(issueComments).values({ companyId: company!.id, issueId: issue!.id, + ...(options.author === "agent" ? { authorType: "agent", authorAgentId: agent!.id } : { authorType: "user", authorUserId: USER }), body: "two helpers" }).returning(); + const record = options.record ?? "match"; + if (record !== "none") { + await recordAntigravitySwarmRequest(db, { companyId: company!.id, issueId: issue!.id, + commentId: record === "other-comment" ? randomUUID() : comment!.id, userId: record === "other-actor" ? "someone-else" : USER }); + } + return { company: company!, agent: agent!, issue: issue!, comment: comment! }; + } + const resolve = (f: Awaited>, overrides: Partial[1]> = {}) => + resolveAntigravitySwarmRun(db, { companyId: f.company.id, issueId: f.issue.id, runId: randomUUID(), agent: f.agent, + context: { antigravitySwarmCommentId: f.comment.id }, remote: false, planning: false, ...overrides }); + + it("selects the swarm for the user's recorded request and logs that it started", async () => { + const f = await seed(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "running", runtimeMode: "native", + runtimeModeResolvedAt: new Date(), nativeIssueId: f.issue.id, responsibleUserId: USER, startedAt: new Date(), contextSnapshot: { issueId: f.issue.id } }).returning(); + expect(await resolve(f, { runId: run!.id })).toBe(true); + const started = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issue.id), eq(activityLog.action, "issue.antigravity_swarm_started"))); + expect(started).toHaveLength(1); + expect(String((started[0]!.details as Record).summary)).toMatch(/does not sandbox the helpers/); + }); + + it.each([ + ["no recorded request", { record: "none" as const }], + ["a record by another actor", { record: "other-actor" as const }], + ["a record for another comment", { record: "other-comment" as const }], + ["an agent-authored comment", { author: "agent" as const }], + ])("never selects the swarm for %s", async (_name, options) => { + expect(await resolve(await seed(options))).toBe(false); + }); + + it("never selects the swarm for a comment an agent wrote on a user's behalf", async () => { + const f = await seed(); + await db.update(issueComments).set({ authorAgentId: f.agent.id }).where(eq(issueComments.id, f.comment.id)); + expect(await resolve(f)).toBe(false); + }); + + it("never selects the swarm for another task's comment, even with a record on this task", async () => { + const f = await seed(); + const [otherIssue] = await db.insert(issues).values({ companyId: f.company.id, title: "Other", status: "todo", assigneeAgentId: f.agent.id }).returning(); + const [otherComment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: otherIssue!.id, authorType: "user", authorUserId: USER, body: "x" }).returning(); + await recordAntigravitySwarmRequest(db, { companyId: f.company.id, issueId: f.issue.id, commentId: otherComment!.id, userId: USER }); + expect(await resolve(f, { context: { antigravitySwarmCommentId: otherComment!.id } })).toBe(false); + }); + + it("ignores a wake without the marker, and a marker from another task or company", async () => { + const f = await seed(); + expect(await resolve(f, { context: { commentId: f.comment.id, wakeCommentId: f.comment.id } })).toBe(false); + const other = await seed(); + expect(await resolve(f, { context: { antigravitySwarmCommentId: other.comment.id } })).toBe(false); + expect(await resolve(other, { companyId: f.company.id })).toBe(false); + }); + + it.each([ + ["a remote environment", { remote: true }, /this computer/], + ["Plan mode", { planning: true }, /Plan mode/], + ])("refuses in plain language in %s instead of running an ordinary request", async (_name, overrides, message) => { + await expect(resolve(await seed(), overrides)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(message) }); + }); + + it("refuses when the flag is off", async () => { + const f = await seed(); + await instanceSettingsService(db).updateExperimental({ enableAntigravitySwarm: false }); + try { + await expect(resolve(f)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/not turned on/) }); + } finally { + await instanceSettingsService(db).updateExperimental({ enableAntigravitySwarm: true }); + } + expect((await db.select().from(activityLog).where(eq(activityLog.action, ANTIGRAVITY_SWARM_REQUESTED_ACTION))).length).toBeGreaterThan(0); + }); +}); diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts index efbd2259fa7..c9982b453c2 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -1,4 +1,4 @@ -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, isNotNull, isNull, sql } from "drizzle-orm"; import { activityLog, agents, issueComments, type Db } from "@paperclipai/db"; import { logActivity } from "./activity-log.js"; import { instanceSettingsService } from "./instance-settings.js"; @@ -96,7 +96,8 @@ export async function resolveAntigravitySwarmRun(db: Db, input: { const commentId = requestedAntigravitySwarmCommentId(input.context); if (!commentId) return false; const [requested] = await db.select({ id: activityLog.id }).from(activityLog) - .innerJoin(issueComments, and(eq(issueComments.id, commentId), eq(issueComments.issueId, input.issueId), eq(issueComments.companyId, input.companyId))) + .innerJoin(issueComments, and(eq(issueComments.id, commentId), eq(issueComments.issueId, input.issueId), eq(issueComments.companyId, input.companyId), + isNotNull(issueComments.authorUserId), isNull(issueComments.authorAgentId))) .where(and(eq(activityLog.companyId, input.companyId), eq(activityLog.action, ANTIGRAVITY_SWARM_REQUESTED_ACTION), eq(activityLog.entityId, input.issueId), eq(activityLog.actorType, "user"), eq(activityLog.actorId, issueComments.authorUserId), sql`${activityLog.details}->>'commentId' = ${commentId}`)) diff --git a/server/src/services/heartbeat/queue.test.ts b/server/src/services/heartbeat/queue.test.ts index 766ad8a37ff..8a9374e4011 100644 --- a/server/src/services/heartbeat/queue.test.ts +++ b/server/src/services/heartbeat/queue.test.ts @@ -1635,3 +1635,12 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { expect(deps.executeRun).not.toHaveBeenCalled(); }); }); + +describe("a /swarm request survives wake coalescing", () => { + const swarm = { issueId: "issue-1", wakeReason: "issue_commented", wakeCommentId: "c-swarm", antigravitySwarmCommentId: "c-swarm" }; + const ordinary = { issueId: "issue-1", wakeReason: "issue_commented", wakeCommentId: "c-later" }; + it("keeps the swarm marker whichever comment arrived first, so the merged run selects its own swarm", () => { + expect(mergeCoalescedContextSnapshot(swarm, ordinary)).toMatchObject({ antigravitySwarmCommentId: "c-swarm" }); + expect(mergeCoalescedContextSnapshot(ordinary, swarm)).toMatchObject({ antigravitySwarmCommentId: "c-swarm" }); + }); +}); diff --git a/server/src/services/native-runtime/first-turn-queued-input.test.ts b/server/src/services/native-runtime/first-turn-queued-input.test.ts index b86b869b85c..c46f5050cc7 100644 --- a/server/src/services/native-runtime/first-turn-queued-input.test.ts +++ b/server/src/services/native-runtime/first-turn-queued-input.test.ts @@ -10,7 +10,7 @@ import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; import { undeliveredLegacyUserCommentIds } from "../explicit-native-continuation.js"; import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js"; import { - claimFirstTurnQueuedInput, firstTurnClaimedCommentIds, firstTurnTakesAllQueuedComments, runAcceptsFirstTurnQueuedInput, + claimFirstTurnQueuedInput, deferredWakeJoinsFirstTurn, firstTurnClaimedCommentIds, firstTurnTakesAllQueuedComments, runAcceptsFirstTurnQueuedInput, } from "./first-turn-queued-input.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -187,3 +187,17 @@ describe.skipIf(!support.supported)("first-turn queued input", () => { commentIds: [withFile] })]).toEqual([]); }); }); + +describe("a /swarm request never joins another run's first turn", () => { + const user = "user-1"; + const commentId = "6f1c1b0e-5a52-4b0a-9a51-0d6c9c3b2f11"; + const wake = (context: Record) => ({ + agentId: "agent-1", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: user, reason: "issue_commented", + payload: { issueId: "issue-1", commentId, mutation: "comment", _paperclipWakeContext: { wakeReason: "issue_commented", commentId, wakeCommentId: commentId, wakeCommentIds: [commentId], ...context } }, + }); + it("keeps the swarm request for its own run selection", () => { + const run = { agentId: "agent-1", responsibleUserId: user }; + expect(deferredWakeJoinsFirstTurn(wake({}), run)).toBe(true); + expect(deferredWakeJoinsFirstTurn(wake({ antigravitySwarmCommentId: commentId }), run)).toBe(false); + }); +}); diff --git a/server/src/services/native-runtime/first-turn-queued-input.ts b/server/src/services/native-runtime/first-turn-queued-input.ts index 0987ede9f31..c3c2e217f27 100644 --- a/server/src/services/native-runtime/first-turn-queued-input.ts +++ b/server/src/services/native-runtime/first-turn-queued-input.ts @@ -109,6 +109,8 @@ export function deferredWakeJoinsFirstTurn( reason !== null && COMMENT_WAKE_REASONS.has(reason) && !payload.interactionId && !context.interactionId && !context.interactionStatus && !payload.queuedCommentInterrupt && context.resumeIntent !== true && + // A /swarm request selects its own run (a different provider route). + context.antigravitySwarmCommentId === undefined && !deferredWakeIsChatRequest(payload) && queuedCommentIdsFromWakePayload(payload).length > 0; } diff --git a/tests/runner-e2e/antigravity-swarm-cases.ts b/tests/runner-e2e/antigravity-swarm-cases.ts index b88ddcccf76..a3be530be8f 100644 --- a/tests/runner-e2e/antigravity-swarm-cases.ts +++ b/tests/runner-e2e/antigravity-swarm-cases.ts @@ -18,12 +18,12 @@ export const ANTIGRAVITY_SWARM_CASES = [ ] as const; export const ANTIGRAVITY_SWARM_RECIPE = "doc/plans/2026-11-22-antigravity-qualification.md#swarm-live-proof"; -const LABELS: Record<(typeof ANTIGRAVITY_SWARM_CASES)[number], { label: string; runs: number; issue: "done" | "in_progress" | "todo"; run: "succeeded" | "cancelled" | "failed" }> = { +const LABELS: Record<(typeof ANTIGRAVITY_SWARM_CASES)[number], { label: string; runs: number; issue: RunnerTaskFixture["expectedTerminalState"]["issue"]; run: "succeeded" | "cancelled" | "failed" }> = { "two-helpers-and-verifier": { label: "Two helpers write a.txt and b.txt, a verifier checks both; task Done", runs: 1, issue: "done", run: "succeeded" }, - "stop-mid-swarm": { label: "Stop mid-swarm stops every helper and leaves no process", runs: 1, issue: "todo", run: "cancelled" }, + "stop-mid-swarm": { label: "Stop mid-swarm stops every helper and leaves no process", runs: 1, issue: "in_progress", run: "cancelled" }, "process-loss-retry": { label: "Kill the CLI mid-swarm, Retry starts a fresh swarm in the same task folder", runs: 2, issue: "done", run: "succeeded" }, "follow-up-after-swarm": { label: "An ordinary follow-up after a swarm runs on the registry route", runs: 2, issue: "done", run: "succeeded" }, - "flag-off-refusal": { label: "With the flag off, /swarm gets the plain 'not available' message and nothing runs", runs: 0, issue: "todo", run: "succeeded" }, + "flag-off-refusal": { label: "With the flag off, /swarm gets the plain 'not available' message and nothing runs", runs: 0, issue: "in_progress", run: "succeeded" }, }; export function buildAntigravitySwarmSuite(environments: readonly EnvironmentFixture[]): RunnerSuiteFixture { diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx index 4182010f115..9ddd972efc6 100644 --- a/ui/src/components/task-chat/TaskChatComposer.test.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx @@ -10,7 +10,7 @@ import { instanceExperimentalSettingsSchema, } from "@paperclipai/shared"; import { parsePlanCommand, parseRunnerGoalCommand, TaskChatComposer } from "./TaskChatComposer"; -import { parseSwarmCommand, planSubmission } from "./composer-commands"; +import { parseSwarmCommand, planSubmission, swarmRunSettingsRefusal } from "./composer-commands"; import { ComposerAddMenu } from "./ComposerAddMenu"; import { QuestionForm } from "./QuestionForm"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; @@ -2034,6 +2034,40 @@ describe("TaskChatComposer", () => { expect(container.textContent).toContain("Write what the swarm should do after /swarm."); }); + it("resends a /swarm request with the same request id after a lost receipt and a reload", async () => { + let rejectSend!: (error: Error) => void; + const onAdd = vi.fn().mockReturnValueOnce(new Promise((_, reject) => { rejectSend = reject; })).mockResolvedValue(undefined); + renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn(), draftKey: "swarm-retry" }); + typeText("/swarm write a.txt"); + await act(async () => sendButton().click()); + const attemptId = onAdd.mock.calls[0][4]; + await act(async () => rejectSend(new CommentSubmissionUnknownError())); + expect(loadDraftSubmission("swarm-retry")?.request).toMatchObject({ body: "write a.txt", nativeCommand: "swarm" }); + renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn(), draftKey: "swarm-retry" }); + await flushAsync(); + const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!; + await act(async () => resend.click()); + expect(onAdd).toHaveBeenNthCalledWith(2, "write a.txt", undefined, undefined, undefined, attemptId, undefined, "swarm"); + }); + + it("refuses /swarm in the new-task composer instead of creating an ordinary task", async () => { + const creation = { value: "/swarm write a.txt", 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).not.toHaveBeenCalled(); + expect(container.textContent).toContain("Create the task first, then send /swarm in a comment on it."); + }); + + it("refuses /swarm with a different model or effort chosen for the message", async () => { + const creation = { value: "", onChange: vi.fn(), onSubmit: vi.fn(), submitLabel: "Create", onSelectFiles: vi.fn(), + runSettings: { model: "gemini-4-argon-medium", effort: null, fast: false }, onRunSettingsChange: vi.fn() }; + expect(swarmRunSettingsRefusal(creation.runSettings)).toBe("Swarm uses the agent's configured model. Clear the model and effort choices for this message, then send /swarm."); + expect(swarmRunSettingsRefusal(null)).toBeNull(); + expect(swarmRunSettingsRefusal({ model: null, effort: null, fast: false })).toBeNull(); + }); + it("leaves a /swarm inside the message as ordinary text", async () => { const onAdd = vi.fn().mockResolvedValue(undefined); renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() }); diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index 65fb6c0733a..b2af7b1f3de 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -72,7 +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, parseSwarmCommand, planSubmission, type RunnerGoalComposerCommand } from "./composer-commands"; +import { parseRunnerGoalCommand, parseSwarmCommand, planSubmission, swarmRunSettingsRefusal, type RunnerGoalComposerCommand } from "./composer-commands"; import type { ActionCommandOption } from "@/context/EditorAutocompleteContext"; import { TaskChatComposerTakeoverActionsContext } from "./TaskChatComposerTakeoverContext"; @@ -866,6 +866,11 @@ export function TaskChatComposer({ async function submit() { if (disabled || (pause && !canResetPausedConversation)) return; if (creation) { + // A swarm is started from a comment on an existing task; never create an ordinary task from it. + if (parseSwarmCommand(bodyRef.current)) { + setActionError("Create the task first, then send /swarm in a comment on it."); + return; + } // 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)) @@ -920,6 +925,11 @@ export function TaskChatComposer({ setActionError("Write what the swarm should do after /swarm."); return; } + const swarmSettingsRefusal = swarmCommand ? swarmRunSettingsRefusal(runSettings) : null; + if (swarmSettingsRefusal) { + setActionError(swarmSettingsRefusal); + return; + } if (swarmCommand && showAssignee && assigneeValue !== currentAssigneeValue) { setActionError("Send /swarm without changing the assignee."); return; @@ -1087,7 +1097,7 @@ export function TaskChatComposer({ ...(reassignment ? { reassignment } : {}), ...(attachmentIds.length ? { attachmentIds } : {}), ...(runSettings ? { runSettings: runSettings as unknown as Record } : {}), - ...(swarmCommand ? { nativeCommand: "swarm" } : {}), + ...(swarmCommand ? { nativeCommand: "swarm" as const } : {}), }; if (draftKey) { saveDraft(draftKey, submittedBody); @@ -1097,7 +1107,7 @@ export function TaskChatComposer({ } sentModeChoice.current = { attemptId, generation: submittedModeGeneration }; if (swarmCommand) { - await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId, runSettings ?? undefined, "swarm"); + await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId, undefined, "swarm"); } else if (runSettings) { await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId, runSettings); } else { @@ -1193,7 +1203,7 @@ export function TaskChatComposer({ submission.attemptId, ] as const; try { - if (request.nativeCommand === "swarm") await onAdd(...args, request.runSettings as unknown as ComposerRunSettings | undefined, "swarm"); + if (request.nativeCommand === "swarm") await onAdd(...args, undefined, "swarm"); else if (request.runSettings) await onAdd(...args, request.runSettings as unknown as ComposerRunSettings); else await onAdd(...args); } catch (error) { diff --git a/ui/src/components/task-chat/composer-commands.ts b/ui/src/components/task-chat/composer-commands.ts index 18f2f28b33b..f41c3332b37 100644 --- a/ui/src/components/task-chat/composer-commands.ts +++ b/ui/src/components/task-chat/composer-commands.ts @@ -65,6 +65,13 @@ export function parseSwarmCommand(value: string): { request: string } | null { return command ? { request: command.argument } : null; } +/** A swarm runs on the agent's configured model; a per-message model or effort choice cannot apply. */ +export function swarmRunSettingsRefusal(settings: { model: string | null; effort: string | null; fast: boolean } | null | undefined): string | null { + return settings && (settings.model || settings.effort || settings.fast) + ? "Swarm uses the agent's configured model. Clear the model and effort choices for this message, then send /swarm." + : null; +} + export type PlanSubmission = | { kind: "none" } /** Select Plan mode and send nothing. */ diff --git a/ui/src/lib/composer-draft.test.ts b/ui/src/lib/composer-draft.test.ts index cbad8ff8210..d9fd9157c9a 100644 --- a/ui/src/lib/composer-draft.test.ts +++ b/ui/src/lib/composer-draft.test.ts @@ -202,3 +202,19 @@ describe("replayable comment requests", () => { expect(replayableRequest(loadDraftSubmission(key), "user-1")).toBeUndefined(); }); }); + +describe("a pending /swarm request survives a reload", () => { + const key = "paperclip:issue-comment-draft:swarm-task"; + const attemptId = "6f1c1b0e-5a52-4b0a-9a51-0d6c9c3b2f11"; + beforeEach(() => { localStorage.clear(); sessionStorage.clear(); }); + it("keeps the structured swarm request and its request id for a safe resend", () => { + saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "two helpers write a.txt", nativeCommand: "swarm" } }); + const restored = loadDraftSubmission(key); + expect(restored?.attemptId).toBe(attemptId); + expect(restored?.request).toEqual({ body: "two helpers write a.txt", nativeCommand: "swarm" }); + }); + it("rejects any other native command value", () => { + saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "x", nativeCommand: "plan" as never } }); + expect(loadDraftSubmission(key)?.request).toBeUndefined(); + }); +}); diff --git a/ui/src/lib/composer-draft.ts b/ui/src/lib/composer-draft.ts index f88eb6376fa..4fde51e5988 100644 --- a/ui/src/lib/composer-draft.ts +++ b/ui/src/lib/composer-draft.ts @@ -140,8 +140,9 @@ function isNullableString(value: unknown): value is string | null { export function isComposerSendRequest(value: unknown): value is ComposerSendRequest { if (!value || typeof value !== "object" || Array.isArray(value)) return false; const row = value as Record; - if (!Object.keys(row).every((key) => ["body", "reopen", "reassignment", "attachmentIds", "runSettings"].includes(key))) return false; + if (!Object.keys(row).every((key) => ["body", "reopen", "reassignment", "attachmentIds", "runSettings", "nativeCommand"].includes(key))) return false; if (typeof row.body !== "string") return false; + if (row.nativeCommand !== undefined && row.nativeCommand !== "swarm") return false; if (row.reopen !== undefined && typeof row.reopen !== "boolean") return false; if (row.reassignment !== undefined) { const reassignment = row.reassignment as Record | null; diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsx index 04acb9666c0..bc23782b2b8 100644 --- a/ui/src/pages/InstanceExperimentalSettings.tsx +++ b/ui/src/pages/InstanceExperimentalSettings.tsx @@ -440,7 +440,7 @@ export function InstanceExperimentalSettings() { toggleMutation.mutate({ enableAntigravitySwarm: checked })}