mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-18 06:15:51 +00:00
* fix: harden ACP communication boundaries Harden ACP communication boundaries Remote ACP sessions now cannot widen permission mode through untrusted metadata or client payloads. WebSocket ACP ingress measures payloads by bytes before binary decode, and prompt queue handoff keeps exactly one prompt active while queued prompts are drained FIFO. Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent Constraint: WebSocket payload limits must be byte-based and checked before binary decode Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing Confidence: high Scope-risk: moderate Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build Not-tested: Manual live ACP/RCS session against an external client * fix: restore repository verification gates Keep the full repository test, typecheck, build, and Biome lint gates usable after the ACP fix pass. This commit is intentionally separate from the ACP behavior change: it fixes Windows-safe Langfuse home redaction, removes stale lint suppressions, resolves Biome warning/info diagnostics, and keeps env expansion tests explicit without template-placeholder lint noise. Constraint: The project completion contract requires full typecheck, lint, test, and build evidence Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims Confidence: high Scope-risk: narrow Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build Not-tested: Manual Langfuse export against a real external Langfuse service * fix: harden ACP failure boundaries after review Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter. Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed Confidence: high Scope-risk: moderate Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bunx tsc --noEmit Tested: bunx biome lint src/ packages/acp-link/src/ Tested: bun run test:all Tested: bun run build Not-tested: Manual end-to-end ACP client session over a real editor WebSocket * fix: prevent ACP coverage runs from seeing partial mocks GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module. This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure. Constraint: bun:test mock.module is process-global inside a worker. Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution. Rejected: Keep per-file helper copies | duplication would let restore semantics drift again. Confidence: high Scope-risk: narrow Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests. Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov Tested: bunx tsc --noEmit Tested: bun run lint Tested: git diff --check Not-tested: Linux runner directly before push * fix: normalize ACP bypass requests without warning noise The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path. This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order. Constraint: CI output should not contain expected warning noise for covered policy branches. Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch. Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site. Confidence: high Scope-risk: narrow Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass. Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0 Tested: bun run test:all Tested: bun run lint Tested: bunx tsc --noEmit Tested: git diff --check * fix: harden ACP bypass and CI warning gates ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state. Constraint: CI must stay warning-clean without hiding real ACP permission failures Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path Confidence: high Scope-risk: moderate Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts Tested: bun run test:all Tested: bun run lint Tested: bun run build:vite with zero warning matches Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches Not-tested: GitHub Actions result after this push * fix: remove remaining CI warning noise The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics. Constraint: Do not use shell log filtering to hide warnings after they happen Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find Confidence: high Scope-risk: narrow Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects Tested: bunx tsc --noEmit --pretty false Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts Tested: bun run build:vite with zero warning matches Not-tested: GitHub Actions result after this push * fix: reject unauthorized ACP bypass and harden CI actions ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings. CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token. Constraint: Must not hide warnings with test isolation or log filtering Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope Confidence: high Scope-risk: moderate Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false Tested: bunx tsc --noEmit --pretty false Tested: bun run lint Tested: bun run test:all Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0 Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR * fix: resolve dependency audit findings precisely Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified. Constraint: no audit ignores or warning suppression Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution Confidence: high Scope-risk: moderate Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: keep ACP auth tokens out of URLs Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change. Constraint: token must not be embedded in the URL Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs Confidence: high Scope-risk: moderate Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code Tested: targeted ACP/RCS transport tests Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: normalize WebFetch request headers Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline. Constraint: preserve header semantics without widening the fetch surface Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites Confidence: high Scope-risk: narrow Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically Tested: targeted WebFetch header tests Not-tested: unrelated fetch backend behavior beyond header normalization * fix: harden ACP remote auth surfaces Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist. Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string. Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data. Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries. Confidence: high Scope-risk: moderate Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>. Tested: bunx tsc --noEmit --pretty false Tested: bun run typecheck in packages/remote-control-server Tested: bun run build in packages/acp-link Tested: bun run lint Tested: bun audit Tested: focused RCS/acp-link/web tests, 160 pass Tested: Edge headless browser WebSocket subprotocol handshake Tested: bun run test:all, 3669 pass Tested: bun run build:vite Tested: bun run build Not-tested: Manual end-to-end relay with a live external ACP agent * fix: resolve CI dependency override lookup The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating. Constraint: Do not add a new root dependency for a transitive smoke test. Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync. Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface. Confidence: high Scope-risk: narrow Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting. Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check --------- Co-authored-by: unraid <local@unraid.local>
572 lines
19 KiB
TypeScript
572 lines
19 KiB
TypeScript
// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
|
|
import React, { useMemo } from 'react'
|
|
import { Ansi, Box, Text } from '@anthropic/ink'
|
|
import { FilePathLink } from '../FilePathLink.js'
|
|
import { toInkColor } from '../../utils/ink.js'
|
|
import type { Attachment } from 'src/utils/attachments.js'
|
|
import type { NullRenderingAttachmentType } from './nullRenderingAttachments.js'
|
|
import { useAppState } from '../../state/AppState.js'
|
|
import { getDisplayPath } from 'src/utils/file.js'
|
|
import { formatFileSize } from 'src/utils/format.js'
|
|
import { MessageResponse } from '../MessageResponse.js'
|
|
import { basename, sep } from 'path'
|
|
import { UserTextMessage } from './UserTextMessage.js'
|
|
import { DiagnosticsDisplay } from '../DiagnosticsDisplay.js'
|
|
import { getContentText } from 'src/utils/messages.js'
|
|
import type { Theme } from 'src/utils/theme.js'
|
|
import { UserImageMessage } from './UserImageMessage.js'
|
|
|
|
import { jsonParse } from '../../utils/slowOperations.js'
|
|
import { plural } from '../../utils/stringUtils.js'
|
|
import { isEnvTruthy } from '../../utils/envUtils.js'
|
|
import { isAgentSwarmsEnabled } from '../../utils/agentSwarmsEnabled.js'
|
|
import {
|
|
tryRenderPlanApprovalMessage,
|
|
formatTeammateMessageContent,
|
|
} from './PlanApprovalMessage.js'
|
|
import { BLACK_CIRCLE } from '../../constants/figures.js'
|
|
import { TeammateMessageContent } from './UserTeammateMessage.js'
|
|
import { isShutdownApproved } from '../../utils/teammateMailbox.js'
|
|
import { CtrlOToExpand } from '../CtrlOToExpand.js'
|
|
|
|
import { feature } from 'bun:bundle'
|
|
import { useSelectedMessageBg } from '../messageActions.js'
|
|
|
|
type Props = {
|
|
addMargin: boolean
|
|
attachment: Attachment
|
|
verbose: boolean
|
|
isTranscriptMode?: boolean
|
|
}
|
|
|
|
export function AttachmentMessage({
|
|
attachment,
|
|
addMargin,
|
|
verbose,
|
|
isTranscriptMode,
|
|
}: Props): React.ReactNode {
|
|
const bg = useSelectedMessageBg()
|
|
// Hoisted to mount-time — per-message component, re-renders on every scroll.
|
|
const isDemoEnv = feature('EXPERIMENTAL_SKILL_SEARCH')
|
|
?
|
|
useMemo(() => isEnvTruthy(process.env.IS_DEMO), [])
|
|
: false
|
|
// Handle teammate_mailbox BEFORE switch
|
|
if (isAgentSwarmsEnabled() && attachment.type === 'teammate_mailbox') {
|
|
// Filter out idle notifications BEFORE counting - they are hidden in the UI
|
|
// so showing them in the count would be confusing ("2 messages in mailbox:" with nothing shown)
|
|
const visibleMessages = attachment.messages.filter(msg => {
|
|
if (isShutdownApproved(msg.text)) {
|
|
return false
|
|
}
|
|
try {
|
|
const parsed = jsonParse(msg.text)
|
|
return (
|
|
parsed?.type !== 'idle_notification' &&
|
|
parsed?.type !== 'teammate_terminated'
|
|
)
|
|
} catch {
|
|
return true // Non-JSON messages are visible
|
|
}
|
|
})
|
|
|
|
if (visibleMessages.length === 0) {
|
|
return null
|
|
}
|
|
return (
|
|
<Box flexDirection="column">
|
|
{visibleMessages.map((msg, idx) => {
|
|
// Try to parse as JSON for task_assignment messages
|
|
let parsedMsg: {
|
|
type?: string
|
|
taskId?: string
|
|
subject?: string
|
|
assignedBy?: string
|
|
} | null = null
|
|
try {
|
|
parsedMsg = jsonParse(msg.text)
|
|
} catch {
|
|
// Not JSON, treat as plain text
|
|
}
|
|
|
|
if (parsedMsg?.type === 'task_assignment') {
|
|
return (
|
|
<Box key={idx} paddingLeft={2}>
|
|
<Text>{BLACK_CIRCLE} </Text>
|
|
<Text>Task assigned: </Text>
|
|
<Text bold>#{parsedMsg.taskId}</Text>
|
|
<Text> - {parsedMsg.subject}</Text>
|
|
<Text dimColor> (from {parsedMsg.assignedBy || msg.from})</Text>
|
|
</Box>
|
|
)
|
|
}
|
|
|
|
// Note: idle_notification messages already filtered out above
|
|
|
|
// Try to render as plan approval message (request or response)
|
|
const planApprovalElement = tryRenderPlanApprovalMessage(
|
|
msg.text,
|
|
msg.from,
|
|
)
|
|
if (planApprovalElement) {
|
|
return (
|
|
<React.Fragment key={idx}>{planApprovalElement}</React.Fragment>
|
|
)
|
|
}
|
|
|
|
// Plain text message - sender header with chevron, truncated content
|
|
const inkColor = toInkColor(msg.color)
|
|
const formattedContent =
|
|
formatTeammateMessageContent(msg.text) ?? msg.text
|
|
return (
|
|
<TeammateMessageContent
|
|
key={idx}
|
|
displayName={msg.from}
|
|
inkColor={inkColor}
|
|
content={formattedContent}
|
|
summary={msg.summary}
|
|
isTranscriptMode={isTranscriptMode}
|
|
/>
|
|
)
|
|
})}
|
|
</Box>
|
|
)
|
|
}
|
|
|
|
// skill_discovery rendered here (not in the switch) so the 'skill_discovery'
|
|
// string literal stays inside a feature()-guarded block. A case label can't
|
|
// be conditionally eliminated; an if-body can.
|
|
if (feature('EXPERIMENTAL_SKILL_SEARCH')) {
|
|
if (attachment.type === 'skill_discovery') {
|
|
if (attachment.skills.length === 0) return null
|
|
// Ant users get shortIds inline so they can /skill-feedback while the
|
|
// turn is still fresh. External users (when this un-gates) just see
|
|
// names — shortId is undefined outside ant builds anyway.
|
|
const names = attachment.skills
|
|
.map(s => (s.shortId ? `${s.name} [${s.shortId}]` : s.name))
|
|
.join(', ')
|
|
const firstId = attachment.skills[0]?.shortId
|
|
const hint =
|
|
process.env.USER_TYPE === 'ant' && !isDemoEnv && firstId
|
|
? ` · /skill-feedback ${firstId} 1=wrong 2=noisy 3=good [comment]`
|
|
: ''
|
|
return (
|
|
<Line>
|
|
<Text bold>{attachment.skills.length}</Text> relevant{' '}
|
|
{plural(attachment.skills.length, 'skill')}: {names}
|
|
{hint && <Text dimColor>{hint}</Text>}
|
|
</Line>
|
|
)
|
|
}
|
|
}
|
|
|
|
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- teammate_mailbox/skill_discovery handled before switch
|
|
switch (attachment.type) {
|
|
case 'directory':
|
|
return (
|
|
<Line>
|
|
Listed directory <Text bold>{attachment.displayPath + sep}</Text>
|
|
</Line>
|
|
)
|
|
case 'file':
|
|
case 'already_read_file':
|
|
if (attachment.content.type === 'notebook') {
|
|
return (
|
|
<Line>
|
|
Read <Text bold>{attachment.displayPath}</Text> (
|
|
{attachment.content.file.cells.length} cells)
|
|
</Line>
|
|
)
|
|
}
|
|
if (attachment.content.type === 'file_unchanged') {
|
|
return (
|
|
<Line>
|
|
Read <Text bold>{attachment.displayPath}</Text> (unchanged)
|
|
</Line>
|
|
)
|
|
}
|
|
return (
|
|
<Line>
|
|
Read <Text bold>{attachment.displayPath}</Text> (
|
|
{attachment.content.type === 'text'
|
|
? `${attachment.content.file.numLines}${attachment.truncated ? '+' : ''} lines`
|
|
: formatFileSize(attachment.content.file.originalSize)}
|
|
)
|
|
</Line>
|
|
)
|
|
case 'compact_file_reference':
|
|
return (
|
|
<Line>
|
|
Referenced file <Text bold>{attachment.displayPath}</Text>
|
|
</Line>
|
|
)
|
|
case 'pdf_reference':
|
|
return (
|
|
<Line>
|
|
Referenced PDF <Text bold>{attachment.displayPath}</Text> (
|
|
{attachment.pageCount} pages)
|
|
</Line>
|
|
)
|
|
case 'selected_lines_in_ide':
|
|
return (
|
|
<Line>
|
|
⧉ Selected{' '}
|
|
<Text bold>{attachment.lineEnd - attachment.lineStart + 1}</Text>{' '}
|
|
lines from <Text bold>{attachment.displayPath}</Text> in{' '}
|
|
{attachment.ideName}
|
|
</Line>
|
|
)
|
|
case 'nested_memory':
|
|
return (
|
|
<Line>
|
|
Loaded <Text bold>{attachment.displayPath}</Text>
|
|
</Line>
|
|
)
|
|
case 'relevant_memories':
|
|
// Usually absorbed into a CollapsedReadSearchGroup (collapseReadSearch.ts)
|
|
// so this only renders when the preceding tool was non-collapsible (Edit,
|
|
// Write) and no group was open. Match CollapsedReadSearchContent's style:
|
|
// 2-space gutter, dim text, count only — filenames/content in ctrl+o.
|
|
return (
|
|
<Box
|
|
flexDirection="column"
|
|
marginTop={addMargin ? 1 : 0}
|
|
backgroundColor={bg}
|
|
>
|
|
<Box flexDirection="row">
|
|
<Box minWidth={2} />
|
|
<Text dimColor>
|
|
Recalled <Text bold>{attachment.memories.length}</Text>{' '}
|
|
{attachment.memories.length === 1 ? 'memory' : 'memories'}
|
|
{!isTranscriptMode && (
|
|
<>
|
|
{' '}
|
|
<CtrlOToExpand />
|
|
</>
|
|
)}
|
|
</Text>
|
|
</Box>
|
|
{(verbose || isTranscriptMode) &&
|
|
attachment.memories.map(m => (
|
|
<Box key={m.path} flexDirection="column">
|
|
<MessageResponse>
|
|
<Text dimColor>
|
|
<FilePathLink filePath={m.path}>
|
|
{basename(m.path)}
|
|
</FilePathLink>
|
|
</Text>
|
|
</MessageResponse>
|
|
{isTranscriptMode && (
|
|
<Box paddingLeft={5}>
|
|
<Text>
|
|
<Ansi>{m.content}</Ansi>
|
|
</Text>
|
|
</Box>
|
|
)}
|
|
</Box>
|
|
))}
|
|
</Box>
|
|
)
|
|
case 'dynamic_skill': {
|
|
const skillCount = attachment.skillNames.length
|
|
return (
|
|
<Line>
|
|
Loaded{' '}
|
|
<Text bold>
|
|
{skillCount} {plural(skillCount, 'skill')}
|
|
</Text>{' '}
|
|
from <Text bold>{attachment.displayPath}</Text>
|
|
</Line>
|
|
)
|
|
}
|
|
case 'skill_listing': {
|
|
if (attachment.isInitial) {
|
|
return null
|
|
}
|
|
return (
|
|
<Line>
|
|
<Text bold>{attachment.skillCount}</Text>{' '}
|
|
{plural(attachment.skillCount, 'skill')} available
|
|
</Line>
|
|
)
|
|
}
|
|
case 'agent_listing_delta': {
|
|
if (attachment.isInitial || attachment.addedTypes.length === 0) {
|
|
return null
|
|
}
|
|
const count = attachment.addedTypes.length
|
|
return (
|
|
<Line>
|
|
<Text bold>{count}</Text> agent {plural(count, 'type')} available
|
|
</Line>
|
|
)
|
|
}
|
|
case 'queued_command': {
|
|
const text =
|
|
typeof attachment.prompt === 'string'
|
|
? attachment.prompt
|
|
: getContentText(attachment.prompt) || ''
|
|
const hasImages =
|
|
attachment.imagePasteIds && attachment.imagePasteIds.length > 0
|
|
return (
|
|
<Box flexDirection="column">
|
|
<UserTextMessage
|
|
addMargin={addMargin}
|
|
param={{ text, type: 'text' }}
|
|
verbose={verbose}
|
|
isTranscriptMode={isTranscriptMode}
|
|
/>
|
|
{hasImages &&
|
|
attachment.imagePasteIds?.map(id => (
|
|
<UserImageMessage key={id} imageId={id} />
|
|
))}
|
|
</Box>
|
|
)
|
|
}
|
|
case 'plan_file_reference':
|
|
return (
|
|
<Line>
|
|
Plan file referenced ({getDisplayPath(attachment.planFilePath)})
|
|
</Line>
|
|
)
|
|
case 'invoked_skills': {
|
|
if (attachment.skills.length === 0) {
|
|
return null
|
|
}
|
|
const skillNames = attachment.skills.map(s => s.name).join(', ')
|
|
return <Line>Skills restored ({skillNames})</Line>
|
|
}
|
|
case 'diagnostics':
|
|
return <DiagnosticsDisplay attachment={attachment} verbose={verbose} />
|
|
case 'mcp_resource':
|
|
return (
|
|
<Line>
|
|
Read MCP resource <Text bold>{attachment.name}</Text> from{' '}
|
|
{attachment.server}
|
|
</Line>
|
|
)
|
|
case 'command_permissions':
|
|
// The skill success message is rendered by SkillTool's renderToolResultMessage,
|
|
// so we don't render anything here to avoid duplicate messages.
|
|
return null
|
|
case 'async_hook_response': {
|
|
// SessionStart hook completions are only shown in verbose mode
|
|
if (attachment.hookEvent === 'SessionStart' && !verbose) {
|
|
return null
|
|
}
|
|
// Generally hide async hook completion messages unless in verbose mode
|
|
if (!verbose && !isTranscriptMode) {
|
|
return null
|
|
}
|
|
return (
|
|
<Line>
|
|
Async hook <Text bold>{attachment.hookEvent}</Text> completed
|
|
</Line>
|
|
)
|
|
}
|
|
case 'hook_blocking_error': {
|
|
// Stop hooks are rendered as a summary in SystemStopHookSummaryMessage
|
|
if (
|
|
attachment.hookEvent === 'Stop' ||
|
|
attachment.hookEvent === 'SubagentStop'
|
|
) {
|
|
return null
|
|
}
|
|
// Show stderr to the user so they can understand why the hook blocked
|
|
const stderr = attachment.blockingError.blockingError.trim()
|
|
return (
|
|
<>
|
|
<Line color="error">
|
|
{attachment.hookName} hook returned blocking error
|
|
</Line>
|
|
{stderr ? <Line color="error">{stderr}</Line> : null}
|
|
</>
|
|
)
|
|
}
|
|
case 'hook_non_blocking_error': {
|
|
// Stop hooks are rendered as a summary in SystemStopHookSummaryMessage
|
|
if (
|
|
attachment.hookEvent === 'Stop' ||
|
|
attachment.hookEvent === 'SubagentStop'
|
|
) {
|
|
return null
|
|
}
|
|
// Full hook output is logged to debug log via hookEvents.ts
|
|
return <Line color="error">{attachment.hookName} hook error</Line>
|
|
}
|
|
case 'hook_error_during_execution':
|
|
// Stop hooks are rendered as a summary in SystemStopHookSummaryMessage
|
|
if (
|
|
attachment.hookEvent === 'Stop' ||
|
|
attachment.hookEvent === 'SubagentStop'
|
|
) {
|
|
return null
|
|
}
|
|
// Full hook output is logged to debug log via hookEvents.ts
|
|
return <Line>{attachment.hookName} hook warning</Line>
|
|
case 'hook_success':
|
|
// Full hook output is logged to debug log via hookEvents.ts
|
|
return null
|
|
case 'hook_stopped_continuation':
|
|
// Stop hooks are rendered as a summary in SystemStopHookSummaryMessage
|
|
if (
|
|
attachment.hookEvent === 'Stop' ||
|
|
attachment.hookEvent === 'SubagentStop'
|
|
) {
|
|
return null
|
|
}
|
|
return (
|
|
<Line color="warning">
|
|
{attachment.hookName} hook stopped continuation: {attachment.message}
|
|
</Line>
|
|
)
|
|
case 'hook_system_message':
|
|
return (
|
|
<Line>
|
|
{attachment.hookName} says: {attachment.content}
|
|
</Line>
|
|
)
|
|
case 'hook_permission_decision': {
|
|
const action = attachment.decision === 'allow' ? 'Allowed' : 'Denied'
|
|
return (
|
|
<Line>
|
|
{action} by <Text bold>{attachment.hookEvent}</Text> hook
|
|
</Line>
|
|
)
|
|
}
|
|
case 'task_status':
|
|
return <TaskStatusMessage attachment={attachment} />
|
|
case 'teammate_shutdown_batch':
|
|
return (
|
|
<Box
|
|
flexDirection="row"
|
|
width="100%"
|
|
marginTop={1}
|
|
backgroundColor={bg}
|
|
>
|
|
<Text dimColor>{BLACK_CIRCLE} </Text>
|
|
<Text dimColor>
|
|
{attachment.count} {plural(attachment.count, 'teammate')} shut down
|
|
gracefully
|
|
</Text>
|
|
</Box>
|
|
)
|
|
default:
|
|
// Exhaustiveness: every type reaching here must be in NULL_RENDERING_TYPES.
|
|
// If TS errors, a new Attachment type was added without a case above AND
|
|
// without an entry in NULL_RENDERING_TYPES — decide: render something (add
|
|
// a case) or render nothing (add to the array). Messages.tsx pre-filters
|
|
// these so this branch is defense-in-depth for other render paths.
|
|
//
|
|
// skill_discovery and teammate_mailbox are handled BEFORE the switch in
|
|
// runtime-gated blocks (feature() / isAgentSwarmsEnabled()) that TS can't
|
|
// narrow through — excluded here via type union (compile-time only, no emit).
|
|
attachment.type satisfies
|
|
| NullRenderingAttachmentType
|
|
| 'skill_discovery'
|
|
| 'teammate_mailbox'
|
|
| 'bagel_console'
|
|
return null
|
|
}
|
|
}
|
|
|
|
type TaskStatusAttachment = Extract<Attachment, { type: 'task_status' }>
|
|
|
|
function TaskStatusMessage({
|
|
attachment,
|
|
}: {
|
|
attachment: TaskStatusAttachment
|
|
}): React.ReactNode {
|
|
// For ants, killed task status is shown in the CoordinatorTaskPanel.
|
|
// Don't render it again in the chat.
|
|
if (process.env.USER_TYPE === 'ant' && attachment.status === 'killed') {
|
|
return null
|
|
}
|
|
|
|
// Only access teammate-specific code when swarms are enabled.
|
|
// TeammateTaskStatus subscribes to AppState; by gating the mount we
|
|
// avoid adding a store listener for every non-teammate attachment.
|
|
if (isAgentSwarmsEnabled() && attachment.taskType === 'in_process_teammate') {
|
|
return <TeammateTaskStatus attachment={attachment} />
|
|
}
|
|
|
|
return <GenericTaskStatus attachment={attachment} />
|
|
}
|
|
|
|
function GenericTaskStatus({
|
|
attachment,
|
|
}: {
|
|
attachment: TaskStatusAttachment
|
|
}): React.ReactNode {
|
|
const bg = useSelectedMessageBg()
|
|
const statusText =
|
|
attachment.status === 'completed'
|
|
? 'completed in background'
|
|
: attachment.status === 'killed'
|
|
? 'stopped'
|
|
: attachment.status === 'running'
|
|
? 'still running in background'
|
|
: attachment.status
|
|
return (
|
|
<Box flexDirection="row" width="100%" marginTop={1} backgroundColor={bg}>
|
|
<Text dimColor>{BLACK_CIRCLE} </Text>
|
|
<Text dimColor>
|
|
Task "<Text bold>{attachment.description}</Text>" {statusText}
|
|
</Text>
|
|
</Box>
|
|
)
|
|
}
|
|
|
|
function TeammateTaskStatus({
|
|
attachment,
|
|
}: {
|
|
attachment: TaskStatusAttachment
|
|
}): React.ReactNode {
|
|
const bg = useSelectedMessageBg()
|
|
// Narrow selector: only re-render when this specific task changes.
|
|
const task = useAppState(s => s.tasks[attachment.taskId])
|
|
if (task?.type !== 'in_process_teammate') {
|
|
// Fall through to generic rendering (task not yet in store, or wrong type)
|
|
return <GenericTaskStatus attachment={attachment} />
|
|
}
|
|
const agentColor = toInkColor(task.identity.color)
|
|
const statusText =
|
|
attachment.status === 'completed'
|
|
? 'shut down gracefully'
|
|
: attachment.status
|
|
return (
|
|
<Box flexDirection="row" width="100%" marginTop={1} backgroundColor={bg}>
|
|
<Text dimColor>{BLACK_CIRCLE} </Text>
|
|
<Text dimColor>
|
|
Teammate{' '}
|
|
<Text color={agentColor} bold dimColor={false}>
|
|
@{task.identity.agentName}
|
|
</Text>{' '}
|
|
{statusText}
|
|
</Text>
|
|
</Box>
|
|
)
|
|
}
|
|
// We allow setting dimColor to false here to help work around the dim-bold bug.
|
|
// https://github.com/chalk/chalk/issues/290
|
|
function Line({
|
|
dimColor = true,
|
|
children,
|
|
color,
|
|
}: {
|
|
dimColor?: boolean
|
|
children: React.ReactNode
|
|
color?: keyof Theme
|
|
}): React.ReactNode {
|
|
const bg = useSelectedMessageBg()
|
|
return (
|
|
<Box backgroundColor={bg}>
|
|
<MessageResponse>
|
|
<Text color={color} dimColor={dimColor} wrap="wrap">
|
|
{children}
|
|
</Text>
|
|
</MessageResponse>
|
|
</Box>
|
|
)
|
|
}
|