Files
PaperClipAI/ui/src/components/task-chat/TaskChatBubble.tsx
T
DottaandPaperclip 2043e0c735 fix: repair runner configuration, macOS execution, and artifact galleries (#13062)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent adapters select a provider, a model, and a runtime.
> - Runner conversion rejected existing Claude agents. The model list
mixed providers.
> - The native Claude runner rejected custom models and could not launch
on macOS.
> - This pull request fixes conversion, model selection, and verified
macOS execution.
> - It also groups configuration fields consistently across adapters and
opens artifact images in the task gallery.
> - Operators can change an agent configuration and run the selected
model on their Mac.

## Linked Issues or Issue Description

**What happened?**

Converting an existing Claude agent to Paperclip Runner failed with a
Codex-only restriction. ACPX Claude showed unrelated models and required
`claude-sonnet-5`. Its native runtime rejected macOS. Configuration
mixed common model settings with process controls. Artifact cards
labeled “Open gallery” navigated to attachment URLs instead of opening
the task gallery.

**Expected behavior**

Conversion keeps agent identity and compatible settings. ACPX Claude
uses the normal Claude catalog and accepts typed model IDs. Codex uses
the native runner. The verified Claude runtime can launch on macOS ARM64
and x64. Common configuration sections place the same fields together
across adapters. Artifact images open in the shared task gallery with
navigation and downloads.

**Steps to reproduce**

1. Open the configuration of an existing Claude agent.
2. Convert it to Paperclip Runner.
3. Select ACPX Claude and a different catalog model or a typed model ID.
4. Save the agent and run a disposable task on macOS.
5. Inspect configuration and advanced run-policy controls across
adapters.

**Paperclip version or commit**

The bugs were reproduced on `165ca56a22adb60e5fda56045442d9c8498116a8`.
This branch was rebased onto `7ed122911`.

**Deployment mode**

Built from source. Local test-drive instance on macOS ARM64 with an
isolated database.

Related work: #11798 addresses unsupported ACP session options in the
existing adapter path. #13048 addresses working-folder preservation.
This change fixes native runner configuration and launch behavior.

## What Changed

- Remove the Codex-only conversion restriction. Preserve agent identity,
instructions, directories, credentials, and compatible model settings.
Reset incompatible sessions while retaining history.
- Show ACPX Claude and native Codex as distinct provider choices. Remove
ACPX Codex from advertised configuration. Normalize legacy
configurations before fresh runs without rewriting historical run
descriptors.
- Select model catalogs and cache entries by provider. Support refresh
and typed model IDs. Pass exact Claude IDs through session creation,
model changes, and recovery.
- Add verified macOS ARM64 and x64 Claude SDK snapshots. Bound
executable allocation and total snapshot size. Preserve package checks,
dependency isolation, process ownership, cancellation, and Linux
descriptor loading.
- Probe local runtime readiness. Report remote platform checks as
incomplete until the remote runner verifies its runtime.
- Surface actual model rejection and allow correction and retry.
- Repair missing ACPX goal-capability helpers exposed by the post-rebase
live test. Persist and restore the optional capability without breaking
session startup.
- Put Agent identity first and intentionally remove the Capabilities
editor, as requested. This is removal of UI editing, not relocation:
preserve existing capability metadata and API compatibility without
adding another editor. Use the themed select for configurable permission
modes, with normal text instead of monospace.
- Put model and provider under Adapter. Give environment variables their
own section. Fold command and arguments under Configuration. Fold
lifecycle, timeout, and interrupt grace under Advanced Run Policy. Hide
single-option permission controls.

- Open image and video artifact cards in the existing task gallery,
including cards in the artifacts panel. Chat attachment images use the
same gallery. Preserve standalone media previews and download links.

## Verification

- Rebased focused UI/API/database suites: 293 tests passed.
- Rebased native runtime and ACPX suites: 242 passed, 7 skipped.
- Repository typecheck, build, and token gates passed for the runner
changes. Gallery follow-up UI typecheck, build, and token gates also
passed.
- Follow-up UI suites passed (86 tests), packaging checks passed (14
tests), and the final focused runtime suites passed (126 passed, 7
skipped).
- Linux container isolation and lifecycle fixtures passed before rebase
(57 passed, 2 skipped). Rust ACPX provider-session tests passed after
rebase (8 tests).
- Browser tests completed actual Claude and native Codex tasks on macOS
ARM64. They covered conversion, catalog refresh, a non-default catalog
model, a typed `haiku` ID, save/reload, cancel, follow-up session
continuity, invalid-model errors, and recovery.
- Final-revision live tests completed a typed Claude task, a follow-up
with the same provider session, and a native Codex task on macOS ARM64.
- Browser tests confirmed the moved interrupt-grace field saves and
survives reload. Cross-adapter tests cover Claude, Codex, Gemini,
process, gateway, and schema forms.
- Full local run: 7,080 passed, 30 skipped, and two timeouts. Both
timeout suites passed on isolated rerun (84 tests); the failures were
the plugin login-worker exit diagnostic and the runner real-server
vertical slice.
- Final follow-up checks: 50 registry tests and 45 snapshot/installation
tests passed (6 platform-specific skips). Oversized executable rejection
is covered before allocation or reading; unsupported-platform tests
invoke the real installation probe.
- Runner head `ddb5101c483a297f74875ab96b3c66035b002d50`: all CI gates
green, including full runner verification, repository build, typecheck,
general/serialized server suites, browser tests, and canary dry run. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/34286178670).
- Greptile: 5/5 on that runner head. All four review threads resolved.
Superagent, Socket, and Snyk checks green.
- After snapshot hardening, another real Claude task completed on this
Mac using the rebuilt runtime.

- Gallery follow-up: 148 focused tests passed, covering artifact
selection, shared attachment collections, deduplication, image/video
cards, standalone previews, downloads, and closing. Live browser
verification completed on the settings follow-up: artifact selection,
6-image pagination with wrapping, download action, and closing all
stayed on the same task URL. All checks passed on gallery head
`96136da58ff195bf6ca00b281eb3022ad12d7bd8`: [CI
run](https://github.com/paperclipai/paperclip/actions/runs/34287987536).
Greptile returned 5/5 on that exact head with no unresolved threads.

- Final settings polish: 96 focused tests, UI typecheck/build, and token
gates passed. A real browser walkthrough verified readable permission
options, identity placement, Capabilities removal, and permission
save/reload. Original test-agent permission mode restored. All 31 checks
passed on final head `e46540d6bf32bfb0566dca16b2f4a75ba437618c`: [CI
run](https://github.com/paperclipai/paperclip/actions/runs/34292797886).
Greptile returned 5/5 with no unresolved threads.

## Risks

- Capabilities intentionally has no editable UI field after this change.
Existing values remain readable and API-compatible; removing the field
does not erase stored metadata.

- macOS launch now copies verified package files into private snapshots.
The implementation must retain isolation and clean up snapshots on exit.
- Runtime provider or model changes reset the current session.
Historical runs remain available.
- The macOS x64 SDK executable digest was verified, but a live Intel Mac
run was not available. Linux verification used container fixtures, not a
real Claude task.
- Remote environment tests report a warning when only the platform has
been checked. They do not claim package readiness from the server host.

## Model Used

OpenAI Codex, based on GPT-6. The exact served model identifier and
context-window limit are not exposed in this session. Used reasoning,
repository inspection, code execution, Rust and TypeScript tests, and
browser automation.

## 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 (focused suites and both
timeout suites on rerun; full-run counts above)
- [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-09-08 19:10:09 -05:00

411 lines
15 KiB
TypeScript

import { useContext, useState, type ReactNode } from "react";
import type { IssueAttachment } from "@paperclipai/shared";
import { IssueGalleryContext } from "@/context/IssueGalleryContext";
import { cn } from "@/lib/utils";
import { useStreamlinedTaskChatPresentation } from "./presentation-mode";
import { MarkdownBody } from "@/components/MarkdownBody";
import {
ImageGalleryModal,
type GalleryMediaItem,
} from "@/components/ImageGalleryModal";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { AgentIcon } from "@/components/AgentIconPicker";
import { CommentAttributionChip } from "@/components/CommentAttributionChip";
import {
Attachment,
AttachmentContent,
AttachmentDescription,
AttachmentGroup,
AttachmentMedia,
AttachmentTitle,
AttachmentTrigger,
} from "@/components/ui/attachment";
import {
extractAttachmentRefs,
extractImageRefs,
fileKindForAttachment,
formatFileSize,
hydrateAttachmentRefs,
isImageAttachment,
stripStandaloneImageEmbeds,
} from "./task-chat-attachments";
import { TaskChatSystemNotice } from "./TaskChatSystemNotice";
import type { TaskChatMessageItem } from "./task-chat-model";
interface TaskChatBubbleProps {
item: TaskChatMessageItem;
/** Requeues a blocked task after a no-live-execution-path recovery notice. */
onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;
tryAgainNoLiveExecutionPathPending?: boolean;
/** Disable the entrance animation when replacing an already-visible live response. */
animateEntry?: boolean;
/** Action shown beside the queued state for an interruptible message. */
queuedAction?: ReactNode;
/**
* The settled run turn rendered on this bubble's footer line (round 9):
* replaces the plain timestamp with "2:34 PM · ✓ Worked · 38s · 3 tools"
* (the timestamp leads the summary), expandable to the nested tool history.
* Supplied by TaskChatThreadView when `item.attachedTurn` is set.
*/
attachedTurn?: ReactNode;
/** New-runner Worked header, rendered above the durable final response. */
beforeTurn?: ReactNode;
/** The durable runner turn already owns the shared agent identity row. */
hideAgentIdentity?: boolean;
/**
* copy · 👍 · 👎 controls for an agent bubble's footer line (PAP-413).
* Rendered here only for a runless reply (leading the bare timestamp); when
* an attached turn is present it owns these via its `leading` slot instead,
* so this bubble skips them. Human/system bubbles pass nothing.
*/
actions?: ReactNode;
attachments?: IssueAttachment[];
}
function initialsForName(name: string) {
const parts = name.trim().split(/\s+/);
if (parts.length >= 2) {
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
return name.slice(0, 2).toUpperCase();
}
export function TaskChatAgentIdentity({
agentName,
agentIcon,
onBehalfOfUserName,
}: {
agentName: string;
agentIcon?: string | null;
onBehalfOfUserName?: string;
}) {
return (
<span
className="flex items-center gap-2 px-1"
data-testid="task-chat-agent-identity"
>
<Avatar
size="sm"
className="shrink-0"
data-testid="task-chat-agent-avatar"
>
{agentIcon ? (
<AvatarFallback>
<AgentIcon icon={agentIcon} className="h-3.5 w-3.5" />
</AvatarFallback>
) : (
<AvatarFallback>{initialsForName(agentName)}</AvatarFallback>
)}
</Avatar>
<span className="text-sm font-semibold text-foreground">{agentName}</span>
{onBehalfOfUserName ? (
<CommentAttributionChip
agentName={agentName}
userName={onBehalfOfUserName}
/>
) : null}
</span>
);
}
/**
* Author-typed message row — the primary legibility signal. Human messages sit
* right in a solid accent bubble; agent messages sit directly on the page
* surface with an avatar author header (the agent's assigned icon + name);
* system notices are centered and recede.
*/
function galleryItemForImage(
src: string,
name?: string,
attachment?: ReturnType<typeof hydrateAttachmentRefs>[number],
): GalleryMediaItem {
return {
id: attachment?.id ?? src,
contentPath: attachment?.openPath ?? src,
openPath: attachment?.openPath,
downloadPath: attachment?.downloadPath,
contentType: attachment?.contentType ?? "",
originalFilename: name?.trim() ? name : "image",
};
}
export function TaskChatBubble({
item,
animateEntry = true,
queuedAction,
attachedTurn,
beforeTurn,
hideAgentIdentity = false,
actions,
attachments = [],
onTryAgainNoLiveExecutionPath,
tryAgainNoLiveExecutionPathPending,
}: TaskChatBubbleProps) {
const streamlined = useStreamlinedTaskChatPresentation();
// Task attachments share the page gallery; standalone images retain the bubble viewer.
const openIssueGallery = useContext(IssueGalleryContext);
const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
const openImage = (src: string) => {
if (!openIssueGallery?.(src)) setLightboxSrc(src);
};
if (item.interstitial) {
// Interstitial updates are ephemeral (PAP-361): while streaming the text
// lives on the live parent row's line (TaskChatStatusItem.selfTalk), and
// once finished it renders nowhere — the run log / classic transcript
// remain the archive. Never rendered as a bubble.
return null;
}
if (item.author === "system") {
// Collapsed humanized one-liner, expandable to the full detail (PAP-443).
return (
<TaskChatSystemNotice
item={item}
onTryAgainNoLiveExecutionPath={onTryAgainNoLiveExecutionPath}
tryAgainNoLiveExecutionPathPending={tryAgainNoLiveExecutionPathPending}
/>
);
}
const isHuman = item.author === "human";
// Non-image file references ("[name](/api/attachments/…/content)") render as
// attachment chips under the bubble; link-only lines leave the body text.
const { refs: linkedRefs, text: bodyWithoutAttachmentLinks } =
extractAttachmentRefs(item.text);
const embeddedImageRefs = extractImageRefs(bodyWithoutAttachmentLinks);
const bodyText = stripStandaloneImageEmbeds(bodyWithoutAttachmentLinks);
const hydratedLinkedRefs = hydrateAttachmentRefs(linkedRefs, attachments);
const hydratedEmbeddedRefs = hydrateAttachmentRefs(
embeddedImageRefs,
attachments,
);
const imageRefs = [
...hydratedEmbeddedRefs,
...hydratedLinkedRefs.filter(isImageAttachment),
].filter((ref, index, refs) =>
refs.findIndex((candidate) => candidate.url === ref.url) === index,
);
const attachmentRefs = hydratedLinkedRefs.filter(
(ref) => !isImageAttachment(ref),
);
const galleryItems: GalleryMediaItem[] =
lightboxSrc !== null && !imageRefs.some((ref) => ref.url === lightboxSrc)
? // A clicked image the extractor missed (e.g. inline HTML) still gets a
// single-item lightbox rather than nothing.
[galleryItemForImage(lightboxSrc)]
: imageRefs.map((ref) => galleryItemForImage(ref.url, ref.name, ref));
const lightboxIndex =
lightboxSrc === null
? -1
: Math.max(0, imageRefs.findIndex((ref) => ref.url === lightboxSrc));
return (
<div
className={cn(
"flex w-full flex-col gap-1",
animateEntry && "tc-enter-bubble",
isHuman ? "items-end" : "items-start",
)}
>
{beforeTurn ? <div className="w-full pb-1">{beforeTurn}</div> : null}
{!isHuman && item.authorName && !hideAgentIdentity ? (
<TaskChatAgentIdentity
agentName={item.authorName}
agentIcon={item.agentIcon}
onBehalfOfUserName={item.onBehalfOfUserName}
/>
) : null}
{bodyText.length > 0 ? (
<div
// Stable hook so the TaskChatLab bubble-treatment explorations
// (PAP-501) can scope background/border overrides to the agent
// bubble body without touching the live thread.
data-testid={
isHuman ? "task-chat-human-bubble" : "task-chat-agent-bubble"
}
className={cn(
"break-words py-2 text-sm",
isHuman
? "max-w-(--pct-85) rounded-2xl rounded-br-sm bg-(--liveness-blue) px-3.5 text-white"
: "w-full bg-transparent px-1 text-foreground",
)}
>
<MarkdownBody
// The human bubble sits on the solid --liveness-blue accent, so the
// prose body text must follow the bubble's `text-white` rather than
// the default light-mode prose color (which reads as black on blue).
// `paperclip-markdown-on-accent` flips prose tokens to currentColor
// (== inherited white) in both themes; dark mode was already correct
// only because `prose-invert` happened to lighten the text.
className={isHuman ? "paperclip-markdown-on-accent" : undefined}
softBreaks
linkIssueReferences
onImageClick={openImage}
>
{bodyText}
</MarkdownBody>
</div>
) : null}
{imageRefs.length > 0 ? (
<div
className="flex max-w-(--pct-85) flex-col gap-2"
data-testid="task-chat-bubble-media"
>
<span className="text-xs text-muted-foreground">
Screenshots · {imageRefs.length}
</span>
<div className="grid grid-cols-4 gap-2">
{imageRefs
.slice(0, imageRefs.length > 4 ? 3 : 4)
.map((ref, index) => (
<button
key={ref.url}
type="button"
className="group aspect-video min-w-0 overflow-hidden rounded-md bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Open ${ref.name || `image ${index + 1}`}`}
onClick={() => openImage(ref.url)}
>
<img
src={ref.openPath ?? ref.url}
alt={ref.name}
loading="lazy"
className="h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"
/>
</button>
))}
{imageRefs.length > 4 ? (
<button
type="button"
className="aspect-video min-w-0 rounded-md bg-muted text-sm font-semibold text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Open ${imageRefs.length - 3} more screenshots`}
onClick={() => openImage(imageRefs[3].url)}
>
+{imageRefs.length - 3}
</button>
) : null}
</div>
<span className="truncate text-xs text-muted-foreground">
{imageRefs.map((ref) => ref.name || "image").join(" · ")}
</span>
</div>
) : null}
{attachmentRefs.length > 0 ? (
<div className="flex max-w-(--pct-85) flex-col gap-2">
<span className="text-xs text-muted-foreground">
Files · {attachmentRefs.length}
</span>
<AttachmentGroup data-testid="task-chat-bubble-attachments">
{attachmentRefs.map((ref) => {
const kind = fileKindForAttachment(ref);
const KindIcon = kind.icon;
const size = formatFileSize(ref.byteSize);
return (
<Attachment key={ref.url} size="sm">
<AttachmentMedia>
<KindIcon aria-hidden />
</AttachmentMedia>
<AttachmentContent>
<AttachmentTitle className="max-w-48">
{ref.name}
</AttachmentTitle>
<AttachmentDescription className="max-w-48">
{size ? `${kind.label} · ${size}` : kind.label}
</AttachmentDescription>
</AttachmentContent>
<AttachmentTrigger
aria-label={`Open ${ref.name}`}
render={
<a
href={ref.openPath ?? ref.url}
target="_blank"
rel="noreferrer"
/>
}
/>
</Attachment>
);
})}
</AttachmentGroup>
</div>
) : null}
{!isHuman && item.verificationCaveats?.length ? (
<div
className="mx-1 w-(--sz-calc-7) rounded-md border border-amber-500/25 bg-amber-500/5 px-3 py-2 text-xs"
data-testid="task-chat-verification-caveats"
>
<p className="font-medium text-amber-800 dark:text-amber-200">
Verification caveat
</p>
<ul className="mt-1 space-y-1 text-muted-foreground">
{item.verificationCaveats.map((caveat, index) => (
<li key={`${caveat.commandOrCheck}:${index}`}>
<span className="font-mono text-foreground">
{caveat.commandOrCheck}
</span>
{caveat.reasonCode
? ` · ${caveat.reasonCode.replaceAll("_", " ")}`
: ""}
{caveat.detail ? (
<span className="block">{caveat.detail}</span>
) : null}
</li>
))}
</ul>
</div>
) : null}
{item.optimistic ? (
<span className="flex items-center gap-1 px-1 text-(length:--text-micro) text-muted-foreground">
<span>{item.optimistic === "queued" ? "Queued" : "Sending…"}</span>
{item.optimistic === "queued" ? queuedAction : null}
</span>
) : attachedTurn ? (
// The settled turn takes over the footer line: timestamp + "✓ Worked"
// summary, always visible; expanding stretches beneath the bubble. The
// copy/👍/👎 actions (PAP-413) ride the turn's summary row via its
// `leading` slot — not this wrapper — so they stay anchored to the
// summary line when the tool history expands beneath it.
<div
className="self-stretch"
data-testid="task-chat-bubble-attached-turn"
>
{attachedTurn}
</div>
) : actions ? (
streamlined ? (
<div className="flex w-full items-center justify-between gap-2 px-1">
{item.timestamp ? (
<span className="text-(length:--text-micro) text-muted-foreground">
{item.timestamp}
</span>
) : null}
{actions}
</div>
) : (
<div className="flex items-center gap-1">
{actions}
{item.timestamp ? (
<span className="px-1 text-(length:--text-micro) text-muted-foreground">
{item.timestamp}
</span>
) : null}
</div>
)
) : item.timestamp ? (
// Timestamps are always visible (round 9) — no longer hover-revealed.
<span className="px-1 text-(length:--text-micro) text-muted-foreground">
{item.timestamp}
</span>
) : null}
{lightboxSrc !== null && lightboxIndex >= 0 ? (
<ImageGalleryModal
items={galleryItems}
initialIndex={lightboxIndex}
open
onOpenChange={(open) => {
if (!open) setLightboxSrc(null);
}}
/>
) : null}
</div>
);
}