Files
PaperClipAI/server/src/services/workflows.ts
T
DottaandClaude Opus 5.5 eb5ad4c920 fix(cases): say a Cases-disabled denial is final and name the Experimental setting (#20892)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Cases is an experimental feature; an instance admin turns it on in
Experimental settings
> - When Cases is off, every case and workflow route answers 403 "Cases
are disabled" with no other information
> - A chat agent asked to "open a customer case" could not tell whether
the denial was final or what to offer
> - In one eval run it created a project and a task in place of the
case; in another it spent most of its turn searching routes before it
replied
> - This pull request gives the denial a code and a final, actionable
remediation, like the board-only denial
> - The benefit is a fast, truthful reply that names the setting and
lets the person choose

## Linked Issues or Issue Description

**What happened**
In the chat eval cases.cases-disabled ("Open a customer case for this
bug." with Cases off), the agent got 403 "Cases are disabled". In one
run it then created a project and a bug task without asking. In a later
run it searched many routes and instance settings for about 100 seconds
before it replied.

**Expected behavior**
The denial says that Cases is off, that the denial is final, where an
instance admin turns it on, and that the agent must not create a
substitute record before the person chooses. The agent replies at once
and offers the setting or an ordinary task.

**Steps to reproduce**
1. Turn off Cases in Experimental settings.
2. As an agent, call GET /api/companies/{companyId}/cases.
3. See a bare 403 "Cases are disabled" with no code or remediation.

## What Changed

- Rebased on #20894, which already gave the case routes a
`cases_disabled` code, a final remediation and the hidden-settings
check. This PR moves that remediation into one helper used by every case
and workflow path, and adds: no substitute task or project before the
person chooses, and the offer of an ordinary task.
- New `casesDisabledError()` in `server/src/services/cases-disabled.ts`:
same 403 message, plus `code: "cases_disabled"` and a remediation. The
remediation says the denial is final, forbids a substitute task or
project before the person chooses, links `[Experimental
settings](/<prefix>/company/settings/instance/experimental)`, and offers
an ordinary task.
- Native tool results carry only the error message, so the native case
tools, workflow tools and runner tool authority inline the remediation
in the message (`casesDisabledError({ inlineRemediation: true })`).
- Case routes, workflow service, case handoffs, native case tools,
native workflow tools and the runner tool authority use the helper
instead of a bare `forbidden("Cases are disabled")`.
- Tests: `cases-routes.test.ts` checks the code and remediation;
`native-case-tools.integration.test.ts` checks the native message
carries the remediation (red on master, green here).

## Verification

- `npx vitest run src/__tests__/cases-routes.test.ts
src/services/case-handoffs.test.ts
src/services/native-runtime/native-case-tools.integration.test.ts
src/__tests__/heartbeat-case-handoff.test.ts` (166 passed).
- The cases.cases-disabled chat eval is rerun on a temporary branch;
results are recorded in the PR conversation.

## Risks

- Low risk. The status and message do not change. The error body adds
`code` and `remediation`.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code
execution in Claude Code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:36:08 -06:00

68 lines
3.8 KiB
TypeScript

import { and, asc, eq } from "drizzle-orm";
import { createHash } from "node:crypto";
import { workflows, type Db } from "@paperclipai/db";
import type { z } from "zod";
import type { createWorkflowSchema, updateWorkflowSchema } from "@paperclipai/shared";
import { conflict, notFound } from "../errors.js";
import { casesDisabledError } from "./cases-disabled.js";
import { instanceSettingsService } from "./instance-settings.js";
import { authorizeCaseCreation } from "./case-mutation-authorization.js";
import type { AuthorizationActor } from "./authorization.js";
import { persistActivity, publishActivity } from "./activity-log.js";
export async function requireCasesEnabled(db: Db) {
if (!(await instanceSettingsService(db).getExperimental()).enableCases) throw casesDisabledError();
}
export async function getWorkflow(db: Db, companyId: string, id: string) {
const [row] = await db.select().from(workflows).where(and(eq(workflows.companyId, companyId), eq(workflows.id, id)));
if (!row) throw notFound("Workflow not found");
return row;
}
export async function getWorkflowMetadata(db: Db, companyId: string, id: string) {
const [row] = await db.select({ id: workflows.id, name: workflows.name }).from(workflows)
.where(and(eq(workflows.companyId, companyId), eq(workflows.id, id)));
if (!row) throw notFound("Workflow not found");
return row;
}
export function workflowService(db: Db) {
return {
list: (companyId: string, options: { limit: number; offset: number }) => db.select({
id: workflows.id, companyId: workflows.companyId, name: workflows.name,
createdAt: workflows.createdAt, updatedAt: workflows.updatedAt,
}).from(workflows).where(eq(workflows.companyId, companyId)).orderBy(asc(workflows.name), asc(workflows.id))
.limit(options.limit).offset(options.offset),
async read(companyId: string, id: string, expectedSnapshot?: string) {
const workflow = await getWorkflow(db, companyId, id);
const snapshot = createHash("sha256").update(JSON.stringify(workflow)).digest("hex");
if (expectedSnapshot && expectedSnapshot !== snapshot) throw conflict("Workflow changed; restart read_workflow at offset zero without snapshot");
return { workflow, snapshot };
},
async write(companyId: string, actor: AuthorizationActor, input: z.infer<typeof createWorkflowSchema> | z.infer<typeof updateWorkflowSchema>, id?: string) {
const result = await db.transaction(async transaction => {
const tx = transaction as unknown as Db;
await requireCasesEnabled(tx);
await authorizeCaseCreation(tx, actor, { companyId });
if (id) await getWorkflow(tx, companyId, id);
const who = actor.type === "agent" ? { actorType: "agent" as const, actorId: actor.agentId!, agentId: actor.agentId! }
: { actorType: "user" as const, actorId: actor.userId ?? "board" };
const [row] = id
? await tx.update(workflows).set({ ...input, updatedAt: new Date() })
.where(and(eq(workflows.id, id), eq(workflows.companyId, companyId))).returning()
: await tx.insert(workflows).values({ companyId, ...input as z.infer<typeof createWorkflowSchema>,
createdByAgentId: actor.type === "agent" ? actor.agentId : null,
createdByUserId: actor.type === "board" ? actor.userId : null }).returning();
if (!row) throw notFound("Workflow not found");
const { publication } = await persistActivity(tx, { companyId, ...who, runId: actor.runId ?? null,
action: id ? "workflow.updated" : "workflow.created", entityType: "workflow", entityId: row.id,
details: { name: row.name, promptChanged: input.prompt !== undefined } });
return { row, publication };
});
publishActivity(result.publication);
return result.row;
},
};
}