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 28aa32e7d7. 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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-24 16:05:37 -06:00
1 parent 96eb00e98f
commit 3128be7cda
5 files changed
+51 -4

No files matched your search

+8
View File
@@ -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.
@@ -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);
@@ -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<void>(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);
@@ -16,7 +16,7 @@ type Row = Record<string, any>;
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);
});
@@ -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<typeof hireHandoffMentions>) => {
await page.goto(chatUrl, { waitUntil: "domcontentloaded" });
const before = await api.get<Row | null>(chatPath);
@@ -181,7 +186,13 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target
const state = await waitForIdle(count);
const comments = await api.get<Row[]>(`/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" });