Files
PaperClipAI/ui/src/components/task-chat/task-chat-adapter.test.ts
T
1c366a9059 fix(server): reject invalid agent credentials instead of downgrading to the local user actor (#11589)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server authenticates each agent request in `actorMiddleware`
before it attributes chat comments
> - When an agent bearer token failed verification, the middleware
called `next()` with no error and the request continued without an agent
actor
> - The request then fell back to the local user actor, so the server
stored agent replies as user comments
> - The task chat UI renders user comments in blue bubbles, so agent
messages appeared as blue user bubbles
> - This pull request rejects invalid agent credentials with 401 instead
of a silent downgrade
> - The benefit is that agent messages keep agent attribution, and
broken credentials fail loudly with a clear retry message

## Linked Issues or Issue Description

**What happened?**

A user cancelled an onboarding question card. The agent posted a
follow-up reply. The reply appeared in a blue bubble, which the UI
reserves for human messages. The agent run held an expired local agent
JWT. The auth middleware could not verify the token, called `next()`
without an actor, and the request fell back to the local user identity.
The server stored the agent comment as a user comment.

**Expected behavior**

Agent messages always render as agent bubbles. A request with invalid
agent credentials must fail with 401 so the adapter can refresh
credentials and retry. It must not post content under a human identity.

**Steps to reproduce**

1. Start a local Paperclip instance.
2. Give an agent run an expired or malformed agent JWT.
3. Let the agent post an issue comment through the API bridge.
4. Before this change: the comment is stored with the local user
identity and renders as a blue bubble. After this change: the request
fails with 401 and a message that tells the caller to obtain fresh
credentials.

## What Changed

- `server/src/middleware/auth.ts`: a bearer token that fails
verification now produces a 401 `unauthorized` error instead of a silent
fall-through to the anonymous/local-user actor.
- The 401 message states the cause: expired token, unverifiable token,
empty bearer token, missing agent record, agent record in another
company, terminated agent, or agent pending approval.
- The API-key path now also rejects an agent record whose company does
not match the key.
- `packages/adapter-utils/src/execution-target.ts`: the bridge proxy now
writes a `comment id: <id>` marker to the run log for each posted issue
comment, so misattributed comments can be traced to a run.
- `ui/src/components/task-chat/task-chat-adapter.test.ts`: a regression
test asserts that a recovered `local-board` comment with a derived agent
author renders as an agent bubble, not a user bubble.
- `server/src/__tests__/agent-auth-middleware.test.ts` and
`packages/adapter-utils/src/execution-target-sandbox.test.ts`: new tests
cover each rejection path and the log marker.

## Verification

- Run `pnpm vitest run src/__tests__/agent-auth-middleware.test.ts` in
`server/` — 14 tests pass.
- Run `pnpm vitest run execution-target-sandbox` at the repo root — 44
tests pass.
- Run `pnpm vitest run
src/components/task-chat/task-chat-adapter.test.ts` in `ui/` — 4 tests
pass.
- Manual check: post an issue comment with an expired agent JWT; the API
returns 401 with a retry message and no comment is stored.

## Risks

- Behavioral shift: requests that previously continued as anonymous or
local-user actors after a failed agent-token verification now receive
401. Any caller that relied on the silent downgrade must refresh its
credentials. This is the intended fix, and the adapters already handle
401 with a credential refresh.
- No schema or migration changes. Low risk otherwise.

> 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 (Anthropic), model ID `claude-fable-5`, via Claude Code with
extended thinking and tool use (agent harness with shell, file, and git
tools).

## 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
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 21:36:11 -07:00

104 lines
3.6 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { IssueChatComment } from "@/lib/issue-chat-messages";
import { commentsToTaskChatItems } from "./task-chat-adapter";
describe("commentsToTaskChatItems", () => {
it("classifies a recovered local-board comment as an agent bubble", () => {
const items = commentsToTaskChatItems([{
id: "c-recovered",
body: "Recovered agent reply.",
authorType: "user",
authorUserId: "local-board",
authorAgentId: null,
derivedAuthorAgentId: "agent-1",
createdAt: "2026-08-07T09:00:00.000Z",
} as unknown as IssueChatComment]);
expect(items).toHaveLength(1);
expect(items[0]).toMatchObject({ kind: "message", author: "agent" });
});
it("never tags posted comments interstitial — the run's final reply keeps its bubble", () => {
const comments = [
{
id: "c1",
body: "Here is the finished work.",
authorType: "agent",
authorAgentId: "agent-1",
runId: "run-1",
createdAt: "2026-07-31T12:00:10.000Z",
} as unknown as IssueChatComment,
];
const items = commentsToTaskChatItems(comments);
expect(items).toHaveLength(1);
const item = items[0];
expect(item.kind).toBe("message");
if (item.kind !== "message") return;
expect(item.author).toBe("agent");
expect(item.interstitial).toBeUndefined();
});
it("classifies system comments as system even with a derivable run→agent linkage (PAP-443)", () => {
const comments = [
{
id: "c-sys",
body: "Paperclip automatically retried dispatch, but it still has no live execution path.",
authorType: "system",
authorAgentId: null,
derivedAuthorAgentId: "agent-1",
createdAt: "2026-08-07T09:00:00.000Z",
} as unknown as IssueChatComment,
];
const items = commentsToTaskChatItems(comments);
expect(items).toHaveLength(1);
const item = items[0];
if (item.kind !== "message") throw new Error("expected message item");
expect(item.author).toBe("system");
});
it("carries presentation, metadata, and the raw timestamp for system comments", () => {
const presentation = {
kind: "system_notice",
tone: "warning",
title: "Run recovery",
detailsDefaultOpen: true,
};
const metadata = {
version: 1,
sections: [{ rows: [{ type: "text", label: "Reason", text: "quota" }] }],
};
const comments = [
{
id: "c-sys",
body: "Recovery notice.",
authorType: "system",
presentation,
metadata,
runAgentId: "agent-1",
createdAt: new Date("2026-08-07T09:00:00.000Z"),
} as unknown as IssueChatComment,
{
id: "c-agent",
body: "Agent reply.",
authorType: "agent",
authorAgentId: "agent-1",
presentation: null,
metadata,
createdAt: "2026-08-07T09:01:00.000Z",
} as unknown as IssueChatComment,
];
const items = commentsToTaskChatItems(comments);
const [sys, agent] = items;
if (sys.kind !== "message" || agent.kind !== "message") throw new Error("expected messages");
expect(sys.presentation).toEqual(presentation);
expect(sys.metadata).toEqual(metadata);
expect(sys.runAgentId).toBe("agent-1");
expect(sys.createdAtIso).toBe("2026-08-07T09:00:00.000Z");
// Non-system authors keep the item lean — no structured notice fields.
expect(agent.presentation).toBeUndefined();
expect(agent.metadata).toBeUndefined();
expect(agent.runAgentId).toBeUndefined();
expect(agent.createdAtIso).toBeUndefined();
});
});