From dc8cf1e5d04c196cfbf344723f2594ffeae8ca34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Okan=20Y=C3=BCcel?= Date: Wed, 25 Nov 2026 00:34:11 +0300 Subject: [PATCH 1/5] fix(documents): return the new body only after a document update or restore (#21036) 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 > - Agents and board users keep plans and specs as issue documents, and they change them through the documents API > - An update (`PUT /api/issues/{id}/documents/{key}`) and a revision restore return the saved document > - The service builds that result from the row it read before the write, so the result also carries the old `latestBody` > - A client that reads `latestBody` from the response gets the previous revision's text, next to the new `latestRevisionId` and `latestRevisionNumber` > - This pull request removes the stale field from the update and restore results, so they have the same shape as a document read > - The benefit is that a write response never shows old text as the latest text ## Linked Issues or Issue Description I searched open and closed issues and pull requests for this bug and found no match. The related work below touches the same service, but not this bug: - Refs #18277 (open: locks the document row during upsert and restore; it does not change the result shape) - Refs #18171 and #12015 (plugin upsert drops `baseRevisionId`; a different bug) **What happened?** `PUT /api/issues/{id}/documents/{key}` on an existing document returned 200. The response had the new `body`, `latestRevisionId` and `latestRevisionNumber`. It also had a `latestBody` field with the text of the previous revision. A `GET` on the same document right after returned only the new body. A restore (`POST /api/issues/{id}/documents/{key}/revisions/{revisionId}/restore`) has the same problem. **Expected behavior** The update and restore responses have the same document shape as `GET /api/issues/{id}/documents/{key}` (the shared `IssueDocument` type). That type has `body` and no `latestBody`. No field in the response holds text from an older revision. **Steps to reproduce** 1. Create an issue document with body `A`. 2. Update it with body `B` and `baseRevisionId` set to the current revision. 3. Read the response: `body` is `B`, but `latestBody` is `A`. 4. Restore revision 1. The response `latestBody` is `B`, the body before the restore. **Paperclip version or commit** Seen on a current npm release. Reproduced on `master` at 51d77648bc with the new service test. **Deployment mode** Not deployment-specific. The bug is in `server/src/services/documents.ts`. **Agent adapter(s) involved** Not adapter-specific (core bug). ## What Changed - `server/src/services/documents.ts`: the update path of `upsertIssueDocument` and the `restoreIssueDocumentRevision` path remove `latestBody` from the row they read before the write. Then they spread the remaining fields into the result. The `body` field stays the new text, as before. - `server/src/__tests__/documents-service.test.ts`: a new test updates a document and restores its first revision. It checks that each result is equal to a fresh `getIssueDocumentByKey` read and has no `latestBody` field. ## Verification - Red-green, as AGENTS.md section 10 asks: - Before the fix, the new test failed on the update result: `latestBody: "# Plan"` (the old body) was in the response. - With only the update fix applied, the test failed on the restore result: `latestBody: "# Second plan"` (the body before the restore). - With both fixes, the test passes. - `npx vitest run` on the 9 test files that write or read issue documents through the service and routes: `documents`, `documents-service`, `issue-document-restore-routes`, `document-annotation-routes`, `document-annotations-service`, `artifact-review-documents-service`, `artifact-review-document-routes`, `native-plan-proposal-sync`, `case-mutation-fence.integration`. Result: 9 files, 68 tests passed. - `pnpm --filter @paperclipai/server typecheck` passed. - I did not run `pnpm verify` locally. The change is in a service that the routes import, so the selection is very broad. The required CI checks supply the broad coverage, as AGENTS.md section 7 allows. ## Risks - Low risk. The response no longer has the undocumented `latestBody` field. That field is not in the shared `IssueDocument` type, and after an update or restore it always held old text. A client that read it got wrong data. The routes read `id`, `key`, `title`, `format`, `latestRevisionId`, `latestRevisionNumber` and `body` from the result. Those fields do not change. - No database or migration change. ## Model Used - Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code, with tool use (shell, file edit) and extended thinking. The run did not show the context window size to the model, so I do not state a number. - The model found the cause, wrote the test and the fix, and ran the checks above. ## 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 (no update needed: the documented response shape does not change) - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- .../src/__tests__/documents-service.test.ts | 25 +++++++++++++++++++ server/src/services/documents.ts | 6 +++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/server/src/__tests__/documents-service.test.ts b/server/src/__tests__/documents-service.test.ts index 37909508ec7..c1d76910dbd 100644 --- a/server/src/__tests__/documents-service.test.ts +++ b/server/src/__tests__/documents-service.test.ts @@ -189,6 +189,31 @@ describeEmbeddedPostgres("documentService system issue documents", () => { }); }); + it("returns the saved document from update and restore exactly as a fresh read returns it", async () => { + const { issueId } = await createIssueWithDocuments(); + const original = (await svc.getIssueDocumentByKey(issueId, "plan"))!; + + const updated = await svc.upsertIssueDocument({ + issueId, + key: "plan", + title: "Plan", + format: "markdown", + body: "# Second plan", + baseRevisionId: original.latestRevisionId, + }); + expect(updated.document).toEqual(await svc.getIssueDocumentByKey(issueId, "plan")); + expect(updated.document).not.toHaveProperty("latestBody"); + + const restored = await svc.restoreIssueDocumentRevision({ + issueId, + key: "plan", + revisionId: original.latestRevisionId!, + }); + expect(restored.document.body).toBe(original.body); + expect(restored.document).toEqual(await svc.getIssueDocumentByKey(issueId, "plan")); + expect(restored.document).not.toHaveProperty("latestBody"); + }); + it("locks and unlocks issue documents", async () => { const { issueId } = await createIssueWithDocuments(); diff --git a/server/src/services/documents.ts b/server/src/services/documents.ts index f4d7029149a..1f99f012ef8 100644 --- a/server/src/services/documents.ts +++ b/server/src/services/documents.ts @@ -464,10 +464,11 @@ export function documentService(db: Db) { .set({ updatedAt: now }) .where(eq(issueDocuments.documentId, existing.id)); + const { latestBody: _previousBody, ...existingMetadata } = existing; return { created: false as const, document: { - ...existing, + ...existingMetadata, title: input.title ?? null, format: input.format, body: input.body, @@ -751,11 +752,12 @@ export function documentService(db: Db) { .set({ updatedAt: now }) .where(eq(issueDocuments.documentId, existing.id)); + const { latestBody: _previousBody, ...existingMetadata } = existing; return { restoredFromRevisionId: revision.id, restoredFromRevisionNumber: revision.revisionNumber, document: { - ...existing, + ...existingMetadata, title: revision.title ?? null, format: revision.format, body: revision.body, From ecef06d24673d1d08cb8cd03151bc4b558f0f7a1 Mon Sep 17 00:00:00 2001 From: Oke Iyanuoluwa Enoch <70354778+Iyanuoluwa007@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:36:17 +0000 Subject: [PATCH 2/5] fix(agents): reject a blank taskKey on reset-session instead of resetting all task state (#19282) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Operators can reset an agent's runtime session with `POST /agents/:id/runtime-state/reset-session` > - A `taskKey` scopes the reset to one task. No key resets all task state. > - The schema accepted a whitespace-only `taskKey`, and the route changed it to `null` > - So a blank key took the full-reset path, and the activity entry recorded `taskKey: null` > - This pull request makes the schema trim the key and reject a blank key with a 400 > - The benefit is that a scoped reset request can never become a full reset by accident ## Linked Issues or Issue Description Fixes #19080 Refs #19005 (the parent issue that #19080 was split out of) I searched open and closed PRs for `19080`, `reset-session` and `resetAgentSessionSchema`. I found no related PR. ## What Changed - `resetAgentSessionSchema.taskKey` is now `z.string().trim().min(1).optional().nullable()`. A blank or whitespace-only key fails validation with a 400. An omitted key or `null` still requests the full reset. - The route uses the parsed `taskKey` directly. The schema already trims it, so the route no longer has its own trim-and-null step. - Added tests in `packages/shared/src/validators/agent.test.ts` for omitted, `null`, trimmed and blank keys. ## Verification - `pnpm exec vitest run packages/shared/src/validators/agent.test.ts`: 16 tests pass. - `pnpm exec vitest run cli/src/__tests__/agent-lifecycle.test.ts`: 4 tests pass. The CLI parses its payload with the same schema. - `pnpm --filter @paperclipai/shared typecheck` passes. - I ran the server `tsc` locally. It reported no errors in `server/src/routes/agents.ts`. My local Windows setup cannot build `@paperclipai/paperclip-runner`, so the full server typecheck depends on CI. ## Risks - Low risk. A client that sends `taskKey: ""` or a whitespace-only key now gets a 400 instead of a full reset. The board UI sends `null` or an issue id, and the CLI omits the key when `--task-key` is not set. Neither caller sends a blank key. ## Model Used - Claude Opus 5.5 (Anthropic, model ID `claude-opus-5-5`), used through Claude Code with tool use (shell, file editing). It assisted with code reading, the change, tests and this description. I reviewed the change. ## 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 --- packages/shared/src/validators/agent.test.ts | 18 +++++++++++++++++- packages/shared/src/validators/agent.ts | 2 +- server/src/routes/agents.ts | 5 +---- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/shared/src/validators/agent.test.ts b/packages/shared/src/validators/agent.test.ts index d38767b0c1f..b15ce4e9609 100644 --- a/packages/shared/src/validators/agent.test.ts +++ b/packages/shared/src/validators/agent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { updateAgentSchema } from "./agent.js"; +import { resetAgentSessionSchema, updateAgentSchema } from "./agent.js"; describe("agent update schema", () => { it.each(["paused", "idle", "terminated"])("accepts lifecycle status request %s", status => { @@ -23,3 +23,19 @@ describe("agent update schema", () => { expect(updateAgentSchema.parse({ name: "Renamed", budgetMonthlyCents: 100 })).toEqual({ name: "Renamed", budgetMonthlyCents: 100 }); }); }); + +describe("reset agent session schema", () => { + it.each([{}, { taskKey: null }])("accepts a full reset request: %j", payload => { + expect(resetAgentSessionSchema.parse(payload)).toEqual(payload); + }); + it("trims a task key", () => { + expect(resetAgentSessionSchema.parse({ taskKey: " task-1 " })).toEqual({ taskKey: "task-1" }); + }); + it.each(["", " ", "\t\n"])("rejects a blank task key %j", taskKey => { + const result = resetAgentSessionSchema.safeParse({ taskKey }); + expect(result.success).toBe(false); + if (!result.success) expect(result.error.issues).toEqual(expect.arrayContaining([ + expect.objectContaining({ path: ["taskKey"] }), + ])); + }); +}); diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts index 13ba04317b1..c6c4e351e64 100644 --- a/packages/shared/src/validators/agent.ts +++ b/packages/shared/src/validators/agent.ts @@ -279,7 +279,7 @@ export const wakeAgentSchema = z.object({ export type WakeAgent = z.infer; export const resetAgentSessionSchema = z.object({ - taskKey: z.string().min(1).optional().nullable(), + taskKey: z.string().trim().min(1).optional().nullable(), }); export type ResetAgentSession = z.infer; diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 1d7872b6aed..2063d295b16 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -4509,10 +4509,7 @@ export function agentRoutes( if (!agent) return; await assertBoardCanManageAgentsForCompany(req, agent.companyId); - const taskKey = - typeof req.body.taskKey === "string" && req.body.taskKey.trim().length > 0 - ? req.body.taskKey.trim() - : null; + const taskKey: string | null = req.body.taskKey ?? null; const state = await heartbeat.resetRuntimeSession(id, { taskKey }); await logActivity(db, { From c9edffe60529c9b2bad7e72542be9324399a83f5 Mon Sep 17 00:00:00 2001 From: Stefan Lendl <1321542+stfl@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:39:10 +0100 Subject: [PATCH 3/5] fix(claude-local): label ACP usage rows from the run's AI connection (#20955) 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 > - A `claude_local` agent can run on a managed AI connection. The connection supplies the credentials and the routing, for example OpenRouter or a gateway. > - Each run writes usage rows to the cost ledger. The rows carry a provider, a biller, a billing type and a model. > - The ACP lane of the Claude adapter finds the billing identity from the agent environment only. It treats a run as API-billed only when `ANTHROPIC_API_KEY` is set. > - A managed connection with bearer auth sets `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL`. It does not set `ANTHROPIC_API_KEY`. The run is therefore labeled `anthropic` with the subscription billing type, and the ledger records zero cost. > - The ACP bridge also reports its own model alias (for example `opus`) as the current model. The usage row then names that alias, not the model that the endpoint received. > - This pull request resolves the billing identity from the managed AI connection first. It also names the requested model on usage rows for those runs. > - The benefit is that runs on an api_key connection show as metered API usage with the correct provider and model in Costs. ## Linked Issues or Issue Description Refs #18540 This pull request fixes the labels for the ACP lane. The Claude CLI lane (`resolveClaudeBillingType`) and the price estimate stay open. Related pull requests that I found. None of them changes the ACP billing identity: - #12000 (`fix(claude-local): distrust gateway-reported costs`) is open. It touches the Claude CLI lane and the cost estimate. - #11420 (`fix(pi-local): report a real billing type instead of hardcoding unknown`) is open. It fixes the same kind of label problem in the Pi adapter. The report in #18540 also names a second problem. Claude Code estimates the price with Anthropic list prices. This pull request does not change that estimate. ## What Changed - `claude-local/src/server/acp-billing.ts` (new): `resolveManagedApiKeyBilling` reads the managed AI connection. For an `api_key` connection it returns the billing type `metered_api`. The provider and the biller are the connection provider. Bedrock routing bills `aws_bedrock`. `resolveEnvBillingIdentity` holds the existing env-based classification, moved out of `acp.ts` unchanged. This keeps `acp.ts` under 1,000 lines. - `claude-local/src/server/acp.ts`: `resolveClaudeAcpBillingIdentity` tries the managed connection first. Other runs, subscription connections included, keep the env-based result. - `adapter-utils/src/acpx-engine/execute.ts`: the ACPX billing identity gets an optional `preferRequestedModel` flag. The two accounting-model calls pass it on. - `adapter-utils/src/acpx-engine/accounting-model.ts`: `acpxAccountingModel` takes an options argument. With `preferRequested`, it returns the requested model, or `null` when the run requested none. - Tests: `acp.test.ts` covers gateway, OpenRouter, local, Bedrock and subscription connections. `accounting-model.test.ts` covers the new option. `execute.test.ts` checks that the usage row and the result name the requested model with the flag, and the bridge model without it. ## Verification - `corepack pnpm install --frozen-lockfile`: succeeded. - `corepack pnpm vitest run src/acpx-engine/accounting-model.test.ts src/acpx-engine/execute.test.ts` (in `packages/adapter-utils`): 2 files, 271 tests passed. - `corepack pnpm vitest run src/server/acp.test.ts` (in `packages/adapters/claude-local`): 1 file, 46 tests passed. - `corepack pnpm --filter @paperclipai/adapter-utils typecheck`: passed. - `corepack pnpm --filter @paperclipai/adapter-claude-local typecheck`: passed. - I did not run the full repository test suite. I did not run a live run against OpenRouter. ## Risks - Low risk. The new path applies only when the run config has a managed `api_key` connection. All other runs keep their current labels. A test checks the subscription case. - A run on an api_key connection whose config names no model now records no model on its usage row. Before, the row carried the bridge alias. - A connection that projects `ANTHROPIC_API_KEY` resolved to `api` before and resolves to `metered_api` now. `normalizeLedgerBillingType` in `server/src/services/heartbeat/run-state.ts` maps both values to `metered_api`, and the Anthropic and Codex pricing accept both. The ledger result is the same. - Runs on an api_key connection change from `subscription_included` to `metered_api`. Their cost is no longer forced to zero. Claude Code still supplies the cost estimate. For a routed model, that amount can differ from the amount that the provider bills. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Code (Anthropic) with tool use (shell, file edits, test runs). Claude Fable 5.2 (`claude-fable-5-2`) directed the work. Claude Sonnet 5.5 (`claude-sonnet-5-5`) ported the change to current master and ran the tests. Claude Opus 5.5 (`claude-opus-5-5`) reviewed it. ## 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../src/acpx-engine/accounting-model.test.ts | 10 +++ .../src/acpx-engine/accounting-model.ts | 8 ++- .../src/acpx-engine/execute.test.ts | 28 ++++++++ .../adapter-utils/src/acpx-engine/execute.ts | 5 +- .../claude-local/src/server/acp-billing.ts | 33 +++++++++ .../claude-local/src/server/acp.test.ts | 68 +++++++++++++++++++ .../adapters/claude-local/src/server/acp.ts | 18 ++--- 7 files changed, 154 insertions(+), 16 deletions(-) create mode 100644 packages/adapters/claude-local/src/server/acp-billing.ts diff --git a/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts b/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts index e7bc77e6982..6f989a1252a 100644 --- a/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts +++ b/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts @@ -15,4 +15,14 @@ describe("ACP accounting model", () => { it("does not price a turn that changed models as one model", () => { expect(acpxAccountingModel("gpt-6.1-sol", selected("gpt-6.1-sol"), selected("gpt-6-astra"))).toBeNull(); }); + it("names the requested model over the bridge's alias when the run asks for it", () => { + const options = { preferRequested: true }; + expect(acpxAccountingModel("acme-claude-sonnet-gw", selected("opus"), selected("opus"), options)).toBe("acme-claude-sonnet-gw"); + expect(acpxAccountingModel("acme-claude-sonnet-gw", selected("opus"), selected("sonnet"), options)).toBe("acme-claude-sonnet-gw"); + }); + it("never names the bridge's current model when the run asked for none", () => { + const options = { preferRequested: true }; + expect(acpxAccountingModel("", selected("opus"), selected("opus"), options)).toBeNull(); + expect(acpxAccountingModel(" ", null, selected("opus"), options)).toBeNull(); + }); }); diff --git a/packages/adapter-utils/src/acpx-engine/accounting-model.ts b/packages/adapter-utils/src/acpx-engine/accounting-model.ts index df181bc6bca..94f12c0d330 100644 --- a/packages/adapter-utils/src/acpx-engine/accounting-model.ts +++ b/packages/adapter-utils/src/acpx-engine/accounting-model.ts @@ -2,7 +2,13 @@ import type { AcpRuntimeStatus } from "acpx/runtime"; /** Use provider-selected IDs, including its default. A mid-turn model change * cannot be priced as a single-model receipt; never guess from a display name. */ -export function acpxAccountingModel(requested: string, before: AcpRuntimeStatus | null, after: AcpRuntimeStatus | null): string | null { +export function acpxAccountingModel( + requested: string, + before: AcpRuntimeStatus | null, + after: AcpRuntimeStatus | null, + options: { preferRequested?: boolean } = {}, +): string | null { + if (options.preferRequested) return requested.trim() || null; const pre = before?.models?.currentModelId?.trim(); const post = after?.models?.currentModelId?.trim(); if (pre && post && pre !== post) return null; diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts index 74f3d01a97b..10019f58c2b 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.test.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts @@ -1641,6 +1641,34 @@ describe("shared ACPX engine runtime behavior", () => { expect(statusLine?.text).toContain('"cost"'); }); + it.each([ + { preferRequestedModel: true, expected: "acme-claude-sonnet-gw" }, + { preferRequestedModel: undefined, expected: "opus" }, + ])("labels usage with the model $expected when preferRequestedModel is $preferRequestedModel", async ({ preferRequestedModel, expected }) => { + const root = await makeTempRoot(); + const onUsage = vi.fn(); + const execute = createAcpxEngineExecutor({ + createRuntime: () => ({ + ...buildRuntime(), + getStatus: async () => ({ models: { currentModelId: "opus", availableModelIds: [] } }), + }) as never, + resolveBillingIdentity: () => ({ provider: "anthropic", biller: "anthropic", billingType: "api", preferRequestedModel }), + }); + const result = await execute({ + runId: "run-requested-model", + onUsage, + agent: { id: "agent-1", companyId: "company-1" }, + runtime: {}, + config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state"), model: "acme-claude-sonnet-gw" }, + context: {}, + onLog: async () => {}, + onMeta: async () => {}, + } as never); + expect(result.exitCode).toBe(0); + expect(result.model).toBe(expected); + expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ model: expected, complete: true })); + }); + it.each(["checkpoint", "terminal"])("returns received usage after the %s receipt sink rejects and still closes the runtime", async (failedSave) => { const root = await makeTempRoot(); const close = vi.fn(async () => {}); diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts index 6f0dc54eb4c..7a5f8a7fdef 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.ts @@ -286,6 +286,7 @@ export interface AcpxEngineBillingIdentity { provider?: string | null; biller?: string | null; billingType?: AdapterBillingType | null; + preferRequestedModel?: boolean; } /** @@ -5162,7 +5163,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { // Snapshot pre-turn usage so cumulative agent-reported cost can be // attributed to this run alone. preTurnStatus = await readRuntimeStatus(runtime, sessionHandle); - accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null); + accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null, { preferRequested: billingIdentity?.preferRequestedModel }); // The prepare phase (prompt build + usage snapshot) finished; the turn // phase starts next. await emitPhase("prepare_turn", preparePhaseStart, "ok"); @@ -5454,7 +5455,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { const turnSucceeded = terminal.status === "completed" && !timedOut && !channelLost; // Read usage before the settlement can discard runtime state. const postTurnStatus = await readRuntimeStatus(runtime, sessionHandle); - accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus); + accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus, { preferRequested: billingIdentity?.preferRequestedModel }); const turnUsage = summarizeAcpxTurnUsage({ preStatus: preTurnStatus, postStatus: postTurnStatus, diff --git a/packages/adapters/claude-local/src/server/acp-billing.ts b/packages/adapters/claude-local/src/server/acp-billing.ts new file mode 100644 index 00000000000..e3323dcda47 --- /dev/null +++ b/packages/adapters/claude-local/src/server/acp-billing.ts @@ -0,0 +1,33 @@ +import type { AdapterBillingType } from "@paperclipai/adapter-utils"; +import { parseObject } from "@paperclipai/adapter-utils/server-utils"; + +export function resolveManagedApiKeyBilling( + config: Record, +): { provider: string; biller: string; billingType: AdapterBillingType; preferRequestedModel: true } | null { + const connection = parseObject(config.managedAiConnection); + const provider = typeof connection.provider === "string" ? connection.provider.trim() : ""; + if (connection.method !== "api_key" || !provider) return null; + return { + provider, + biller: parseObject(config.managedAiRouting).kind === "bedrock" ? "aws_bedrock" : provider, + billingType: "metered_api", + preferRequestedModel: true, + }; +} + +export function resolveEnvBillingIdentity( + readEnvValue: (key: string) => string, +): { provider: string; biller: string; billingType: AdapterBillingType } { + const bedrockFlag = readEnvValue("CLAUDE_CODE_USE_BEDROCK"); + const bedrock = bedrockFlag === "1" || bedrockFlag === "true" || Boolean(readEnvValue("ANTHROPIC_BEDROCK_BASE_URL")); + const billingType: AdapterBillingType = bedrock + ? "metered_api" + : readEnvValue("ANTHROPIC_API_KEY") + ? "api" + : "subscription"; + return { + provider: "anthropic", + biller: bedrock ? "aws_bedrock" : "anthropic", + billingType, + }; +} diff --git a/packages/adapters/claude-local/src/server/acp.test.ts b/packages/adapters/claude-local/src/server/acp.test.ts index c5102a71aee..f966b4f4d9f 100644 --- a/packages/adapters/claude-local/src/server/acp.test.ts +++ b/packages/adapters/claude-local/src/server/acp.test.ts @@ -1842,6 +1842,74 @@ describe("resolveClaudeAcpBillingIdentity", () => { }); }); + describe("with a managed AI connection", () => { + const attribution = (overrides: Record) => ({ + connectionId: "conn-1", grantId: "grant-1", mode: "shared", responsibleUserId: null, ...overrides, + }); + + it("labels a gateway api_key connection from the connection, whatever credential env it projects", () => { + delete process.env.ANTHROPIC_API_KEY; + expect( + resolveClaudeAcpBillingIdentity({ + config: { + model: "acme-claude-sonnet-gw", + managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }), + managedAiRouting: { kind: "gateway", auth: "bearer", baseUrl: "https://gateway.example.test", protocol: "messages" }, + env: { ANTHROPIC_AUTH_TOKEN: "token", ANTHROPIC_BASE_URL: "https://gateway.example.test" }, + }, + }), + ).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("bills an OpenRouter connection to OpenRouter", () => { + expect( + resolveClaudeAcpBillingIdentity({ + config: { + managedAiConnection: attribution({ provider: "openrouter", method: "api_key" }), + managedAiRouting: { kind: "openrouter", auth: "bearer" }, + }, + }), + ).toEqual({ provider: "openrouter", biller: "openrouter", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("bills a local-routing connection to its provider", () => { + expect( + resolveClaudeAcpBillingIdentity({ + config: { + managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }), + managedAiRouting: { kind: "local", auth: "none" }, + }, + }), + ).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("keeps Bedrock routing metered", () => { + expect( + resolveClaudeAcpBillingIdentity({ + config: { + managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }), + managedAiRouting: { kind: "bedrock", region: "eu-central-1" }, + }, + }), + ).toEqual({ provider: "anthropic", biller: "aws_bedrock", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("leaves a subscription connection with the labels it always got", () => { + delete process.env.ANTHROPIC_API_KEY; + delete process.env.CLAUDE_CODE_USE_BEDROCK; + delete process.env.ANTHROPIC_BEDROCK_BASE_URL; + const identity = resolveClaudeAcpBillingIdentity({ + config: { + model: "claude-sonnet-5-5", + managedAiConnection: attribution({ provider: "anthropic", method: "subscription" }), + env: { ANTHROPIC_API_KEY: "" }, + }, + }); + expect(identity).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "subscription" }); + expect(identity).not.toHaveProperty("preferRequestedModel"); + }); + }); + it("ignores host env for remote execution targets", () => { process.env.ANTHROPIC_API_KEY = "sk-ant-host-only"; expect( diff --git a/packages/adapters/claude-local/src/server/acp.ts b/packages/adapters/claude-local/src/server/acp.ts index 1a653c05f42..e7494ac5685 100644 --- a/packages/adapters/claude-local/src/server/acp.ts +++ b/packages/adapters/claude-local/src/server/acp.ts @@ -40,6 +40,7 @@ import { asString, parseObject, } from "@paperclipai/adapter-utils/server-utils"; +import { resolveEnvBillingIdentity, resolveManagedApiKeyBilling } from "./acp-billing.js"; import { materializeRemoteClaudeConfig, overrideRemoteClaudeLocalPermissionMode, @@ -177,7 +178,9 @@ export function buildClaudeAcpConfig( export function resolveClaudeAcpBillingIdentity( ctx: Pick & Partial>, -): { provider: string; biller: string; billingType: AdapterBillingType } { +): { provider: string; biller: string; billingType: AdapterBillingType; preferRequestedModel?: true } { + const connection = resolveManagedApiKeyBilling(ctx.config); + if (connection) return connection; const envConfig = parseObject(parseObject(ctx.config).env); const target = readAdapterExecutionTarget({ executionTarget: ctx.executionTarget, @@ -190,18 +193,7 @@ export function resolveClaudeAcpBillingIdentity( const fromHost = considerHostEnv ? process.env[key] : undefined; return typeof fromHost === "string" ? fromHost.trim() : ""; }; - const bedrockFlag = readEnvValue("CLAUDE_CODE_USE_BEDROCK"); - const bedrock = bedrockFlag === "1" || bedrockFlag === "true" || Boolean(readEnvValue("ANTHROPIC_BEDROCK_BASE_URL")); - const billingType: AdapterBillingType = bedrock - ? "metered_api" - : readEnvValue("ANTHROPIC_API_KEY") - ? "api" - : "subscription"; - return { - provider: "anthropic", - biller: bedrock ? "aws_bedrock" : "anthropic", - billingType, - }; + return resolveEnvBillingIdentity(readEnvValue); } /** From 96eb00e98f10fdfaf76e0c0a600450e6d01a9c81 Mon Sep 17 00:00:00 2001 From: Zurva Aziz Date: Tue, 24 Nov 2026 13:44:57 -0800 Subject: [PATCH 4/5] fix(routines): prefer X-Hub-Signature-256 on app_webhook triggers (#18581) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Routines can start from public webhook triggers > - The `app_webhook` signing mode reads a signature from `X-Hub-Signature` or `X-Hub-Signature-256` > - Some senders, such as GitHub, can send both headers on one delivery > - The code reads `X-Hub-Signature` first, and `verifyAppWebhook` accepts only `sha256=` values > - So a SHA-1 value in `X-Hub-Signature` causes a 401, even when the SHA-256 signature is valid > - This pull request reads `X-Hub-Signature-256` first > - The benefit is that senders that send both headers can use `app_webhook` triggers ## Linked Issues or Issue Description Fixes #18565 Related, not duplicates: #16781, #1892. ## What Changed - `firePublicTrigger` now prefers `X-Hub-Signature-256` over `X-Hub-Signature` in `app_webhook` mode. - Added tests for both headers, each header alone, an invalid SHA-256 header, and a SHA-1 header alone. ## Verification - Codex ran these checks in its cloud sandbox. - Run from `server/`: `../node_modules/.bin/vitest run src/__tests__/routines-service.test.ts` - Result: 85 tests passed, 0 failed, 0 skipped. Embedded Postgres ran. - With the fix reversed, 2 of the 5 new tests failed. With the fix restored, all 5 passed. - The server TypeScript check passed. - The full workspace typecheck did not finish because `cargo` was not installed in the test environment. - The full build and the repository-wide tests were not run. CI must confirm them. ## Risks - Low risk. The change affects only `app_webhook` mode. - Behavior change: a delivery with a valid `sha256=` value in `X-Hub-Signature` and an invalid `X-Hub-Signature-256` value was accepted before. It now gets a 401. - SHA-1 signatures stay rejected. This is an interoperability fix, not a security fix. ## Model Used - Implementation and tests: OpenAI Codex (cloud). The session did not show the exact model ID, context window, or reasoning mode. - Review and pull request text: Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [ ] 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 (targeted suite only, in the Codex sandbox, see Verification) - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes (not needed, the existing docs stay correct) - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge --- server/src/__tests__/routines-service.test.ts | 48 +++++++++++++++++++ server/src/services/routines.ts | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/routines-service.test.ts b/server/src/__tests__/routines-service.test.ts index 4a8718230cf..2c73797cc9c 100644 --- a/server/src/__tests__/routines-service.test.ts +++ b/server/src/__tests__/routines-service.test.ts @@ -2904,6 +2904,54 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => { }); + it.each([ + "both signature headers", + "SHA-256 header only", + "legacy header only", + ])("accepts a signed app webhook with %s", async (headers) => { + const { svc, routine, trigger, secretMaterial } = await firefliesFixture(false, "app_webhook"); + const payload = { event: "deployment.completed", deployment_id: "deploy-headers" }; + const rawBody = Buffer.from(JSON.stringify(payload)); + const secret = secretMaterial!.webhookSecret; + const signature = `sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`; + const result = await svc.firePublicTrigger(trigger.publicId!, { + rawBody, + payload, + hubSignatureHeader: headers === "legacy header only" ? undefined : signature, + firefliesSignatureHeader: headers === "SHA-256 header only" + ? undefined + : headers === "legacy header only" + ? signature + : `sha1=${createHmac("sha1", secret).update(rawBody).digest("hex")}`, + }); + + expect(result.status).toBe("issue_created"); + const runs = await svc.listRuns(routine.id); + expect(runs).toHaveLength(1); + expect(runs[0].triggerPayload).toEqual(payload); + }); + + it.each(["invalid SHA-256 header", "SHA-1 header only"])( + "rejects an app webhook with %s despite valid bearer authorization", + async (headers) => { + const { svc, routine, trigger, secretMaterial } = await firefliesFixture(false, "app_webhook"); + const payload = { event: "deployment.completed", deployment_id: "deploy-invalid" }; + const rawBody = Buffer.from(JSON.stringify(payload)); + const secret = secretMaterial!.webhookSecret; + + await expect(svc.firePublicTrigger(trigger.publicId!, { + rawBody, + payload, + authorizationHeader: `Bearer ${secret}`, + hubSignatureHeader: headers === "SHA-1 header only" ? undefined : `sha256=${"0".repeat(64)}`, + firefliesSignatureHeader: headers === "SHA-1 header only" + ? `sha1=${createHmac("sha1", secret).update(rawBody).digest("hex")}` + : `sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`, + })).rejects.toMatchObject({ status: 401 }); + expect(await svc.listRuns(routine.id)).toEqual([]); + }, + ); + it("dispatches one Fireflies run for concurrent retries and passes meeting metadata", async () => { const { svc, routine, trigger, delivery, wakeups } = await firefliesFixture(); const results = await Promise.all([ diff --git a/server/src/services/routines.ts b/server/src/services/routines.ts index 8b935241c49..b7c69a9233d 100644 --- a/server/src/services/routines.ts +++ b/server/src/services/routines.ts @@ -3319,7 +3319,7 @@ export function routineService( appDelivery = verifyAppWebhook({ secret: await resolveTriggerSecret(trigger, routine.companyId), publicId, authorization: input.authorizationHeader, - signature: input.firefliesSignatureHeader ?? input.hubSignatureHeader, + signature: input.hubSignatureHeader ?? input.firefliesSignatureHeader, rawBody: input.rawBody, idempotencyKey: input.idempotencyKey, }); } else if (trigger.signingMode === "fireflies_hmac") { From 3128be7cda54ed125197aa3e7205009ec7d060ba Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:05:37 -0600 Subject: [PATCH 5/5] fix(e2e): preserve exact spacing around handoff mentions (#22825) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Product journeys check that a person can hire and delegate through chat. > - The journey selects real agent and project mentions in the composer. > - Each selection inserts a trailing space for the next typed word. > - The helper then types the complete next source slice, including its own whitespace. > - This pull request removes the inserted space through normal keyboard editing before continuing. > - The benefit is one exact saved message with the existing strict identity and count checks. ## Linked Issues or Issue Description **What happened?** The hiring journey saves two spaces after its agent mention and an unwanted space before the comma after its project mention. Its exact saved-body assertion fails after the delegated task completes. The retained historical observation lacks the original message comparison. This PR reproduces the spacing defect directly in the production composer; it does not claim those missing historical inputs were recovered. **Expected behavior** Normal mention selection must preserve the exact requested body, including whitespace and punctuation, and save it exactly once. **Steps to reproduce** Run the production composer browser spec with the quoted checklist reference. Before the repair, the saved message has an extra space after each selected mention. After the repair, the body matches exactly. **Paperclip version or commit** Reproduced from source at 28aa32e7d7ba72d8f83c03ffd45625c096813e6b. The affected source files were unchanged on current master before publication. **Deployment mode** Local Linux Chromium control with the real production and streamlined composers. No model or staging credentials. Related merged #22821 repairs a separate routine journey. ## What Changed - Check the collapsed caret before removing exactly one editor-added space. Refuse to send if the caret does not match. - Preserve exact agent/project mention identities and the single-message assertion. - Retain private byte counts, SHA-256 body hashes, IDs and comparison results before grading. Do not retain raw bodies. - Extend the real composer test with the quoted checklist reference. Keep wrong-agent, duplicate and missing-project rejection. ## Verification - Red: the production composer browser check failed with extra spaces around both mention chips. - Green: all 6 composer browser checks pass with the corrected helper. - All 75 focused hiring flow and evidence tests pass. A changed-body control proves the failure receipt survives grading. - Local test-project typecheck could not complete: the host killed the compiler with SIGKILL. `pnpm verify --explain` could not select checks because the managed Git storage guard rejects `git ls-files`. Neither attempt is a pass. - Final head `99338b2a3f0717489f09cd949353ed2d12248e3e`: [selected CI](https://github.com/paperclipai/paperclip/actions/runs/45491682386) passes, including Typecheck + Release Registry, four support shards, six Runner package shards, static checks and aggregate verify. Build and unrelated suites are skipped by the test-only path policy. Greptile is 5/5 on this head. There are no review threads. No new paid test, protected pin update or staging deployment was made. ## Risks - The browser helper depends on the shipped mention insertion caret contract. A missing trailing space stops the send instead of deleting a mention. - The historical cause remains an inference from an independently reproduced defect. A future full run must establish staging acceptance. ## Model Used OpenAI GPT-6 through Codex, with reasoning, source editing, shell tools and Chromium. The runtime does not expose a more specific model revision. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- tests/runner-e2e/SECURITY.md | 8 ++++++++ .../runner-e2e/hire-delegate-composer.spec.ts | 2 +- .../hire-delegate-composer.ts | 12 +++++++++++ .../hire-delegate-flow.test.ts | 20 +++++++++++++++++-- .../product-journeys/hire-delegate-flow.ts | 13 +++++++++++- 5 files changed, 51 insertions(+), 4 deletions(-) diff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.md index 0ffe1996445..2eb2b121014 100644 --- a/tests/runner-e2e/SECURITY.md +++ b/tests/runner-e2e/SECURITY.md @@ -829,3 +829,11 @@ unknown outside heartbeat accounting, never zero. This candidate includes only the focused local native-probe prerequisite from core PR18103; all candidate outcomes are separate from frozen39e qualification. Source acceptance is not permission to run the unused initial. + + +The hiring journey retains `hire-user-message-checks.json` before grading each +submitted message. Its private receipt contains comment IDs, exact byte counts, +SHA-256 body hashes and comparison results. It contains no raw message bodies or +provider session state. Mention insertion uses ordinary keyboard editing to +remove the editor-added space before typing the next exact source slice. The +exact saved-body check and single-message count remain required. diff --git a/tests/runner-e2e/hire-delegate-composer.spec.ts b/tests/runner-e2e/hire-delegate-composer.spec.ts index 1fd0aa3140d..d5a599edf65 100644 --- a/tests/runner-e2e/hire-delegate-composer.spec.ts +++ b/tests/runner-e2e/hire-delegate-composer.spec.ts @@ -11,7 +11,7 @@ test.afterAll(async () => { await fixture?.close(); }); const references = hireHandoffMentions({ companyId: r.companyId, leadId: r.leadId, projectId: r.projectId, campaignId: r.campaignId }, r.agentId, { id: r.agentId, companyId: r.companyId, reportsTo: r.leadId, name: `Morgan Reviewer ${r.campaignId}`, icon: "code" }, { id: r.projectId, companyId: r.companyId, name: `Journey QA hire-delegate-reuse ${r.campaignId}`, color: "#336699" }); -const message = (review = false) => `Have the existing ${references.teammate} ${review ? "review the checklist on QA-1 and write a separate saved review" : "write a concise launch checklist as a saved Paperclip document"}. Create exactly one task in ${references.project}, already assigned to that teammate when it is created. Link the result here.`; +const message = (review = false) => `Have the existing ${references.teammate} ${review ? "review the checklist on QA-1 and write a separate saved review" : 'write a concise launch checklist as a saved Paperclip document with the line "Reference: HIREjourney1deadbeef"'}. Create exactly one task in ${references.project}, already assigned to that teammate when it is created. Link the result here.`; async function open(page: Page, key: string, variant = "valid", mode = "production") { const url = new URL("/__hire.html", fixture.url); url.searchParams.set("case", key); url.searchParams.set("variant", variant); url.searchParams.set("mode", mode); await page.goto(url.href); diff --git a/tests/runner-e2e/product-journeys/hire-delegate-composer.ts b/tests/runner-e2e/product-journeys/hire-delegate-composer.ts index d94986723a6..97607109665 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-composer.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-composer.ts @@ -36,6 +36,18 @@ export async function sendHireHandoffMessage(page: Page, text: string, reference await expect(chip).toBeVisible({ timeout: timeout() }); if (await chip.getAttribute("href") !== token.href) throw new JourneyError("failed", "hire_handoff_mention_mismatch"); await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))); + // Mention insertion leaves the caret after one editor-added space. Remove + // that space through the normal keyboard path; the next source slice owns + // its exact whitespace (including punctuation directly after a mention). + const hasInsertedSpace = await editable.evaluate(element => { + const selection = element.ownerDocument.getSelection(); + const node = selection?.anchorNode; + return Boolean(selection?.isCollapsed && node?.nodeType === Node.TEXT_NODE + && element.contains(node) && selection.anchorOffset > 0 + && node.textContent?.slice(selection.anchorOffset - 1, selection.anchorOffset) === " "); + }); + if (!hasInsertedSpace) throw new JourneyError("failed", "hire_handoff_caret_mismatch"); + await editable.press("Backspace"); offset = token.at + token.markdown.length; } const suffix = text.slice(offset); diff --git a/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts b/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts index c954a0083dd..8bfbc140fb2 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts @@ -16,7 +16,7 @@ type Row = Record; const directories: string[] = []; afterEach(async () => { vi.mocked(sendChatMessage).mockReset(); await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); }); -async function fixture(options: { readError?: Error; mutate?(agents: Row[], tasks: Row[]): void; ownError?: Error; firstSendError?: Error; connectionList?: Row; connectionReadError?: Error } = {}) { +async function fixture(options: { storedBody?: string; readError?: Error; mutate?(agents: Row[], tasks: Row[]): void; ownError?: Error; firstSendError?: Error; connectionList?: Row; connectionReadError?: Error } = {}) { const campaignId = "journey-1-deadbeef", names = hireDelegateNames(campaignId), owned: Row[] = [], comments: Row[] = []; const binding = { connectionId: "approved" }, lead = { id: "lead", companyId: "company", name: `Lead ${campaignId}`, permissions: { canCreateAgents: true }, runtimeConfig: { aiConnection: binding } }; const hire = { id: "hired", companyId: "company", name: names.hire, reportsTo: lead.id, adapterType: "paperclip_runner", @@ -35,7 +35,7 @@ async function fixture(options: { readError?: Error; mutate?(agents: Row[], task const stop = new JourneyError("failed", "test_stop_before_delegation"); vi.mocked(sendChatMessage).mockImplementation(async (_page, text) => { if (sent) throw stop; - sent = true; if (options.firstSendError) throw options.firstSendError; comments.push({ id: "user-comment", authorUserId: "user", body: text }); + sent = true; if (options.firstSendError) throw options.firstSendError; comments.push({ id: "user-comment", authorUserId: "user", body: options.storedBody ?? text }); }); const api = { origin: "https://qa.example.test", async get(route: string) { if (route === "/api/instance/settings/experimental") return { enableAgentChat: true }; @@ -355,3 +355,19 @@ it.each(["earlier-handoff", "foreign-company", "foreign-chat", "wrong-run", "for { companyId: "company", chatId: "chat", runId: "callback" })).toBe(false); expect(clicked).toBe(false); }); + + +it("retains an exact failed message comparison before grading, without retaining raw bodies", async () => { + const f = await fixture({ storedBody: "A changed private fixture message" }); + await expect(f.run()).rejects.toMatchObject({ code: "hire_user_messages_stored_once" }); + const raw = await readFile(path.join(f.directory, "hire-user-message-checks.json"), "utf8"); + const receipt = JSON.parse(raw); + expect(receipt).toMatchObject({ schema: "paperclip.product-journey.hire-user-messages/v1", checks: [ + { turn: 1, matches: false, added: [{ id: "user-comment", matches: false }] }, + ] }); + expect(receipt.checks[0].expected.sha256).toMatch(/^[a-f0-9]{64}$/); + expect(receipt.checks[0].added[0].body.sha256).not.toBe(receipt.checks[0].expected.sha256); + expect(raw).not.toContain("private fixture message"); + expect(raw).not.toContain("Hire exactly one"); + expect(sendChatMessage).toHaveBeenCalledTimes(1); +}); diff --git a/tests/runner-e2e/product-journeys/hire-delegate-flow.ts b/tests/runner-e2e/product-journeys/hire-delegate-flow.ts index e6f61f494e0..af231adb320 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-flow.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-flow.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import { isDeepStrictEqual } from "node:util"; import path from "node:path"; @@ -172,6 +173,10 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target } throw new JourneyError("failed", awaitingReply ? "hire_completion_reply_missing" : "hire_chat_not_completed"); }; + const messageChecks: Row[] = []; + const bodyReceipt = (body: unknown) => typeof body === "string" ? { + byteSize: Buffer.byteLength(body), sha256: createHash("sha256").update(body).digest("hex"), + } : null; const turn = async (text: string, count: number, handoff?: ReturnType) => { await page.goto(chatUrl, { waitUntil: "domcontentloaded" }); const before = await api.get(chatPath); @@ -181,7 +186,13 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target const state = await waitForIdle(count); const comments = await api.get(`/api/issues/${state.chat.id}/comments?order=asc`); const added = comments.filter(row => row.authorUserId === context.user.id && !prior.some(old => old.id === row.id)); - check("hire-user-messages-stored-once", added.length === 1 && added[0].body === text); + const matches = added.length === 1 && added[0].body === text; + messageChecks.push({ turn: messageChecks.length + 1, expected: bodyReceipt(text), matches, + added: added.map(row => ({ id: row.id, body: bodyReceipt(row.body), matches: row.body === text })) }); + // Keep the actual comparison inputs before a failed grade, without copying + // message bodies, private session state or credentials into this receipt. + await retain("hire-user-message-checks.json", { schema: "paperclip.product-journey.hire-user-messages/v1", checks: messageChecks }); + check("hire-user-messages-stored-once", matches); return state; }; await session.own({ kind: "agent", name: names.hire, journeyId: "hire-delegate-reuse" });