Files
PaperClipAI/ui/src/components/task-chat/task-chat-adapter.ts
T
DottaandPaperclip 955501a75a fix(ui): do not render fast_response comments as New session markers (#23778)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent Chat renders conversation comments through
`commentsToTaskChatItems` in the task-chat UI adapter.
> - Fast-response acknowledgements (added in #15748) store
`conversationSessionGeneration` on `issue_comments` (including `0`) to
track which session they belong to.
> - The UI adapter treated any comment with
`conversationSessionGeneration != null` as a `/new` session-start
divider.
> - As a result, fast-response acknowledgements disappeared and rendered
as "New session · Earlier messages and files are still available."
dividers even when the user never ran `/new`.
> - This pull request narrows session-start marker detection so only
non-fast-response comments with `conversationSessionGeneration > 0`
render as session-start dividers.
> - The benefit is that fast-response acknowledgements display as agent
bubbles while real `/new` resets keep their session divider.

## Linked Issues or Issue Description

Refs #15748

**What happened?**

In Agent Chat, when Experimental Fast Responses is enabled, sending a
normal message causes a "New session · Earlier messages and files are
still available." divider to appear immediately after the user message,
even though the user never sent `/new` and the conversation session
generation stayed at `0`.

**Expected behavior**

Fast-response acknowledgements render as normal `fast_response` agent
bubbles. Only `/new` session-reset boundary comments render as "New
session" dividers.

**Steps to reproduce**

1. Enable Experimental Fast Responses on an instance and configure a
fast-response model.
2. Open an Agent Chat thread and send a normal message (not `/new`).
3. Observe that the `origin: "fast_response"` acknowledgement comment
has `conversationSessionGeneration: 0` (or the current generation `>=
1`) and renders as a "New session" marker instead of the acknowledgement
text.

**Paperclip version or commit**

Reproduced on `master` (commit `314bc70c1`).

**Deployment mode**

Self-hosted server

## What Changed

- Export `isConversationSessionStartComment` in
`ui/src/components/task-chat/task-chat-adapter.ts`, requiring
`comment.origin !== "fast_response"` and `typeof
comment.conversationSessionGeneration === "number" &&
comment.conversationSessionGeneration > 0`.
- Use `isConversationSessionStartComment` in `commentsToTaskChatItems`
(`ui/src/components/task-chat/task-chat-adapter.ts`) and in
`isHistoricalNotice`
(`ui/src/components/task-chat/status-relevance.ts`).
- Add regression unit tests in
`ui/src/components/task-chat/task-chat-adapter.test.ts` covering
`fast_response` comments in generation `0` and generation `1`, real
`/new` session boundaries in generation `1`, and non-reset
generation-`0` comments.

## Verification

- Verified red before the fix and green after the fix with `pnpm vitest
run ui/src/components/task-chat/task-chat-adapter.test.ts
ui/src/components/task-chat/status-relevance.test.ts
ui/src/components/TaskChatThread.test.tsx` (3 test files passed, 469
passed, 1 skipped).
- Verified UI typecheck with `pnpm --filter @paperclipai/ui typecheck`
(passed).

## Risks

Low risk. Only `/new` boundary comments ever stamp a positive
`conversationSessionGeneration` on a non-`fast_response` comment
(`issues.conversationSessionGeneration` starts at `0` and `/new`
increments it before writing the boundary comment). Existing
`fast_response` rows already stored in Postgres immediately render
properly with no migration required.

## Model Used

Google Gemini (Antigravity, medium reasoning effort, with code
execution, file editing, and read-only browser inspection).

## 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>
2026-12-04 15:54:56 -06:00

184 lines
8.1 KiB
TypeScript

/**
* Live adapter: normalize the existing IssueChatComment stream (including
* optimistic echoes) into the redesign's TaskChatItem[] model. This is the
* seam that lets the new render layer show live task data without touching the
* comment data pipeline. Rich agent-run streaming (thinking/tool/diff) is
* demonstrated in the harness and layered onto this adapter as a later step;
* the baseline live thread renders the author-typed message history + optimistic
* echo, which is the core legibility win.
*/
import type { Agent } from "@paperclipai/shared";
import type { IssueChatComment } from "@/lib/issue-chat-messages";
import { resolveCommentAttribution } from "@/lib/comment-attribution";
import { resolveIssueChatHumanAuthor } from "@/lib/issue-chat-human-author";
import { resolveActorProfileAttribution } from "../CommentStructuredMeta";
import type { CompanyUserProfile } from "@/lib/company-members";
import type { TaskChatAuthorKind, TaskChatItem, TaskChatMessageItem } from "./task-chat-model";
export interface TaskChatAdapterContext {
agentMap?: Map<string, Agent>;
userLabelMap?: ReadonlyMap<string, string> | null;
userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
currentUserId?: string | null;
/**
* Task's current assignee. Agent comments from anyone else are cross-issue
* writes and get a "for {user}" attribution chip (the open cross-task write design (attribution)).
*/
issueAssigneeAgentId?: string | null;
verificationCaveatsByRunId?: ReadonlyMap<string, TaskChatMessageItem["verificationCaveats"]>;
}
function effectiveAgentId(comment: IssueChatComment): string | null {
return comment.authorAgentId ?? comment.derivedAuthorAgentId ?? null;
}
function authorKind(comment: IssueChatComment): TaskChatAuthorKind {
// The server-authored presentation contract wins over attribution. Some
// control-plane notices keep the run agent as their author for audit and
// authorization, but they must still use the system-notice renderer.
// System authorship also wins over any derivable run→agent linkage
// (PAP-443): recovery notices carry a derivedAuthorAgentId but must not
// render as agent bubbles.
if (
comment.presentation?.kind === "system_notice" ||
comment.authorType === "system"
) {
return "system";
}
if (effectiveAgentId(comment)) return "agent";
if (comment.authorType === "user") return "human";
return "agent";
}
/** Shared bubble-footer time format ("2:34 PM") — also used by the description bubble (PAP-375). */
export function formatTaskChatTimestamp(value: unknown): string | undefined {
if (!value) return undefined;
const d = value instanceof Date ? value : new Date(value as string);
if (Number.isNaN(d.getTime())) return undefined;
return d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}
/** Keep every comment footer on the same compact, user-visible timestamp. */
export function formatTaskChatCommentTimestamp(
comment: IssueChatComment,
_kind: TaskChatAuthorKind,
): string | undefined {
return formatTaskChatTimestamp(comment.createdAt);
}
export function isConversationSessionStartComment(
comment: Pick<IssueChatComment, "conversationSessionGeneration" | "origin">,
): boolean {
return (
comment.origin !== "fast_response" &&
typeof comment.conversationSessionGeneration === "number" &&
comment.conversationSessionGeneration > 0
);
}
export function commentsToTaskChatItems(
comments: IssueChatComment[],
ctx: TaskChatAdapterContext = {},
): TaskChatItem[] {
const items: TaskChatItem[] = [];
for (const comment of comments) {
if (comment.deletedAt) continue;
if (isConversationSessionStartComment(comment)) {
items.push({ id: comment.id, kind: "marker", variant: "session_start", label: "New session",
detail: "Earlier messages and files are still available.", createdAtIso: new Date(comment.createdAt).toISOString() });
continue;
}
const kind = authorKind(comment);
let authorName: string | undefined;
let agentIcon: string | null | undefined;
let onBehalfOfUserName: string | undefined;
const humanAuthor = kind === "human" ? resolveIssueChatHumanAuthor({
authorUserId: comment.authorUserId,
authorName: comment.authorUserId ? ctx.userLabelMap?.get(comment.authorUserId) : null,
actorProfile: comment.actorProfile,
currentUserId: ctx.currentUserId,
userProfileMap: ctx.userProfileMap,
}) : undefined;
const actorProfileAttribution = kind === "human"
? resolveActorProfileAttribution({
actorProfile: comment.actorProfile,
authorUserId: comment.authorUserId,
userLabelMap: ctx.userLabelMap,
userProfileMap: ctx.userProfileMap,
})
: null;
if (kind === "agent") {
const agentId = effectiveAgentId(comment);
authorName = (agentId && ctx.agentMap?.get(agentId)?.name) || "Agent";
agentIcon = agentId ? ctx.agentMap?.get(agentId)?.icon : undefined;
onBehalfOfUserName = resolveCommentAttribution({
authorAgentId: agentId,
onBehalfOfUserId: comment.onBehalfOfUserId ?? null,
issueAssigneeAgentId: ctx.issueAssigneeAgentId,
resolveUserLabel: (userId) => ctx.userLabelMap?.get(userId),
})?.userName;
} else if (kind === "human") {
authorName = humanAuthor!.authorName;
}
const queued = comment.queueState === "queued" || comment.clientStatus === "queued";
const optimistic =
queued
? "queued"
: comment.clientStatus === "pending"
? "pending"
: undefined;
const createdAtIso =
comment.createdAt instanceof Date
? comment.createdAt.toISOString()
: comment.createdAt
? String(comment.createdAt)
: undefined;
// Durable run-authored comments already carry their source run directly.
// Activity-derived `runId` is a useful fallback for older rows, but it may
// arrive later (or be omitted entirely for server-materialized final
// replies). Prefer the stored provenance so settled-response decorations
// such as verification caveats are never lost.
const sourceRunId = comment.createdByRunId
?? comment.runId
?? comment.derivedCreatedByRunId
?? null;
items.push({
id: comment.id || comment.clientId || `${comment.createdAt}`,
renderKey: comment.clientId ?? comment.id,
kind: "message",
author: kind,
authorName,
...(humanAuthor ? {
authorUserId: comment.authorUserId,
authorAvatarUrl: humanAuthor.avatarUrl,
isCurrentUser: humanAuthor.isCurrentUser,
} : {}),
...(actorProfileAttribution ? { actorProfileAttribution } : {}),
...(comment.kvLabels && Object.keys(comment.kvLabels).length > 0 ? { kvLabels: comment.kvLabels } : {}),
...(comment.schemaBlocks && comment.schemaBlocks.length > 0 ? { schemaBlocks: comment.schemaBlocks } : {}),
agent: effectiveAgentId(comment) ? ctx.agentMap?.get(effectiveAgentId(comment)!) ?? { id: effectiveAgentId(comment)! } : undefined,
text: comment.body,
origin: comment.origin ?? "comment",
chatMessage: comment.metadata?.chatMessage,
sourceChannel: kind === "human" ? comment.metadata?.sourceChannel : undefined,
...(kind === "human" && comment.nativeCommand === "swarm" ? { nativeCommand: "swarm" as const } : {}),
timestamp: formatTaskChatCommentTimestamp(comment, kind),
optimistic,
queueTargetRunId: queued ? comment.queueTargetRunId ?? null : null,
verificationCaveats: sourceRunId
? ctx.verificationCaveatsByRunId?.get(sourceRunId)
: undefined,
agentIcon,
onBehalfOfUserName,
...(kind === "agent" && sourceRunId ? { sourceRunId } : {}),
// System notices carry their structured hints through to the render
// layer (PAP-443); other authors keep the item lean.
presentation: kind === "system" ? comment.presentation ?? null : undefined,
metadata: kind === "system" ? comment.metadata ?? null : undefined,
runAgentId: kind === "system" ? comment.runAgentId ?? null : undefined,
createdAtIso,
});
}
return items;
}