claude-code-best/src/components/Spinner.tsx
Dosion c2ac9a74c1
fix: resolve dependency audit findings precisely (#361)
* 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>
2026-04-26 19:49:54 +08:00

617 lines
23 KiB
TypeScript

// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
import { Box, Text, stringWidth } from '@anthropic/ink'
import * as React from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import {
computeGlimmerIndex,
computeShimmerSegments,
SHIMMER_INTERVAL_MS,
} from '../bridge/bridgeStatusUtil.js'
import { feature } from 'bun:bundle'
import { getKairosActive, getUserMsgOptIn } from '../bootstrap/state.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js'
import { isEnvTruthy } from '../utils/envUtils.js'
import { count } from '../utils/array.js'
import sample from 'lodash-es/sample.js'
import {
formatDuration,
formatNumber,
formatSecondsShort,
} from '../utils/format.js'
import type { Theme } from 'src/utils/theme.js'
import { activityManager } from '../utils/activityManager.js'
import { getSpinnerVerbs } from '../constants/spinnerVerbs.js'
import { MessageResponse } from './MessageResponse.js'
import { TaskListV2 } from './TaskListV2.js'
import { useTasksV2 } from '../hooks/useTasksV2.js'
import type { Task } from '../utils/tasks.js'
import { useAppState } from '../state/AppState.js'
import { useTerminalSize } from '../hooks/useTerminalSize.js'
import { getDefaultCharacters, type SpinnerMode } from './Spinner/index.js'
import { SpinnerAnimationRow } from './Spinner/SpinnerAnimationRow.js'
import { useSettings } from '../hooks/useSettings.js'
import { isInProcessTeammateTask } from '../tasks/InProcessTeammateTask/types.js'
import { isBackgroundTask } from '../tasks/types.js'
import { getAllInProcessTeammateTasks } from '../tasks/InProcessTeammateTask/InProcessTeammateTask.js'
import { getEffortSuffix } from '../utils/effort.js'
import { getMainLoopModel } from '../utils/model/model.js'
import { getViewedTeammateTask } from '../state/selectors.js'
import { TEARDROP_ASTERISK } from '../constants/figures.js'
import figures from 'figures'
import {
getCurrentTurnTokenBudget,
getTurnOutputTokens,
} from '../bootstrap/state.js'
import { TeammateSpinnerTree } from './Spinner/TeammateSpinnerTree.js'
import { useAnimationFrame } from '@anthropic/ink'
import { getGlobalConfig } from '../utils/config.js'
export type { SpinnerMode } from './Spinner/index.js'
const DEFAULT_CHARACTERS = getDefaultCharacters()
const SPINNER_FRAMES = [
...DEFAULT_CHARACTERS,
...[...DEFAULT_CHARACTERS].reverse(),
]
type Props = {
mode: SpinnerMode
loadingStartTimeRef: React.RefObject<number>
totalPausedMsRef: React.RefObject<number>
pauseStartTimeRef: React.RefObject<number | null>
spinnerTip?: string
responseLengthRef: React.RefObject<number>
apiMetricsRef?: React.RefObject<
Array<{
ttftMs: number;
firstTokenTime: number;
lastTokenTime: number;
responseLengthBaseline: number;
endResponseLength: number;
}>
>
overrideColor?: keyof Theme | null
overrideShimmerColor?: keyof Theme | null
overrideMessage?: string | null
spinnerSuffix?: string | null
verbose: boolean
hasActiveTools?: boolean
/** Leader's turn has completed (no active query). Used to suppress stall-red spinner when only teammates are running. */
leaderIsIdle?: boolean
}
// Thin wrapper: branches on isBriefOnly so the two variants have independent
// hook call chains. Without this split, toggling /brief mid-render would
// violate Rules of Hooks (the inner variant calls ~10 more hooks).
export function SpinnerWithVerb(props: Props): React.ReactNode {
const isBriefOnly = useAppState(s => s.isBriefOnly)
// REPL overrides isBriefOnly→false when viewing a teammate transcript
// (see isBriefOnly={viewedTeammateTask ? false : isBriefOnly}). That
// prop isn't threaded here, so replicate the gate from the store —
// teammate view needs the real spinner (which shows teammate status).
const viewingAgentTaskId = useAppState(s => s.viewingAgentTaskId)
// Hoisted to mount-time — this component re-renders at animation framerate.
const briefEnvEnabled =
feature('KAIROS') || feature('KAIROS_BRIEF')
?
useMemo(() => isEnvTruthy(process.env.CLAUDE_CODE_BRIEF), [])
: false
// Runtime gate mirrors isBriefEnabled() but inlined — importing from
// BriefTool.ts would leak tool-name strings into external builds. Single
// spinner instance → hooks stay unconditional (two subs, negligible).
if (
(feature('KAIROS') || feature('KAIROS_BRIEF')) &&
(getKairosActive() ||
(getUserMsgOptIn() &&
(briefEnvEnabled ||
getFeatureValue_CACHED_MAY_BE_STALE('tengu_kairos_brief', false)))) &&
isBriefOnly &&
!viewingAgentTaskId
) {
return (
<BriefSpinner mode={props.mode} overrideMessage={props.overrideMessage} />
)
}
return <SpinnerWithVerbInner {...props} />
}
function SpinnerWithVerbInner({
mode,
loadingStartTimeRef,
totalPausedMsRef,
pauseStartTimeRef,
spinnerTip,
responseLengthRef,
overrideColor,
overrideShimmerColor,
overrideMessage,
spinnerSuffix,
verbose,
hasActiveTools = false,
leaderIsIdle = false,
}: Props): React.ReactNode {
const settings = useSettings()
const reducedMotion = settings.prefersReducedMotion ?? false
// NOTE: useAnimationFrame(50) lives in SpinnerAnimationRow, not here.
// This component only re-renders when props or app state change —
// it is no longer on the 50ms clock. All `time`-derived values
// (frame, glimmer, stalled intensity, token counter, thinking shimmer,
// elapsed-time timer) are computed inside the child.
const tasks = useAppState(s => s.tasks)
const viewingAgentTaskId = useAppState(s => s.viewingAgentTaskId)
const expandedView = useAppState(s => s.expandedView)
const showExpandedTodos = expandedView === 'tasks'
const showSpinnerTree = expandedView === 'teammates'
const selectedIPAgentIndex = useAppState(s => s.selectedIPAgentIndex)
const viewSelectionMode = useAppState(s => s.viewSelectionMode)
// Get foregrounded teammate (if viewing a teammate's transcript)
const foregroundedTeammate = viewingAgentTaskId
? getViewedTeammateTask({ viewingAgentTaskId, tasks })
: undefined
const { columns } = useTerminalSize()
const tasksV2 = useTasksV2()
// Track thinking status: 'thinking' | number (duration in ms) | null
// Shows each state for minimum 2s to avoid UI jank
const [thinkingStatus, setThinkingStatus] = useState<
'thinking' | number | null
>(null)
const thinkingStartRef = useRef<number | null>(null)
useEffect(() => {
let showDurationTimer: ReturnType<typeof setTimeout> | null = null
let clearStatusTimer: ReturnType<typeof setTimeout> | null = null
if (mode === 'thinking') {
// Started thinking
if (thinkingStartRef.current === null) {
thinkingStartRef.current = Date.now()
setThinkingStatus('thinking')
}
} else if (thinkingStartRef.current !== null) {
// Stopped thinking - calculate duration and ensure 2s minimum display
const duration = Date.now() - thinkingStartRef.current
const elapsed = Date.now() - thinkingStartRef.current
const remainingThinkingTime = Math.max(0, 2000 - elapsed)
thinkingStartRef.current = null
// Show "thinking..." for remaining time if < 2s elapsed, then show duration
const showDuration = (): void => {
setThinkingStatus(duration)
// Clear after 2s
clearStatusTimer = setTimeout(setThinkingStatus, 2000, null)
}
if (remainingThinkingTime > 0) {
showDurationTimer = setTimeout(showDuration, remainingThinkingTime)
} else {
showDuration()
}
}
return () => {
if (showDurationTimer) clearTimeout(showDurationTimer)
if (clearStatusTimer) clearTimeout(clearStatusTimer)
}
}, [mode])
// Find the current in-progress task and next pending task
const currentTodo = tasksV2?.find(
task => task.status !== 'pending' && task.status !== 'completed',
)
const nextTask = findNextPendingTask(tasksV2)
// Use useState with initializer to pick a random verb once on mount
const [randomVerb] = useState(() => sample(getSpinnerVerbs()))
// Leader's own verb (always the leader's, regardless of who is foregrounded)
const leaderVerb =
overrideMessage ??
currentTodo?.activeForm ??
currentTodo?.subject ??
randomVerb
const effectiveVerb =
foregroundedTeammate && !foregroundedTeammate.isIdle
? (foregroundedTeammate.spinnerVerb ?? randomVerb)
: leaderVerb
const message = effectiveVerb + '…'
// Track CLI activity when spinner is active
useEffect(() => {
const operationId = 'spinner-' + mode
activityManager.startCLIActivity(operationId)
return () => {
activityManager.endCLIActivity(operationId)
}
}, [mode])
const effortValue = useAppState(s => s.effortValue)
const effortSuffix = getEffortSuffix(getMainLoopModel(), effortValue)
// Check if any running in-process teammates exist (needed for both modes)
const runningTeammates = getAllInProcessTeammateTasks(tasks).filter(
t => t.status === 'running',
)
const hasRunningTeammates = runningTeammates.length > 0
const allIdle = hasRunningTeammates && runningTeammates.every(t => t.isIdle)
// Gather aggregate token stats from all running swarm teammates
// In spinner-tree mode, skip aggregation (teammates have their own lines in the tree)
let teammateTokens = 0
if (!showSpinnerTree) {
for (const task of Object.values(tasks)) {
if (isInProcessTeammateTask(task) && task.status === 'running') {
if (task.progress?.tokenCount) {
teammateTokens += task.progress.tokenCount
}
}
}
}
// Stale read of the refs for showBtwTip below — we're off the 50ms clock
// so this only updates when props/app state change, which is sufficient for
// a coarse 30s threshold.
const elapsedSnapshot =
pauseStartTimeRef.current !== null
? pauseStartTimeRef.current -
loadingStartTimeRef.current -
totalPausedMsRef.current
: Date.now() - loadingStartTimeRef.current - totalPausedMsRef.current
// Leader token count for TeammateSpinnerTree — read raw (non-animated) from
// the ref. The tree is only shown when teammates are running; teammate
// progress updates to s.tasks trigger re-renders that keep this fresh.
const leaderTokenCount = Math.round(responseLengthRef.current / 4)
const defaultColor: keyof Theme = 'claude'
const defaultShimmerColor = 'claudeShimmer'
const messageColor = overrideColor ?? defaultColor
const shimmerColor = overrideShimmerColor ?? defaultShimmerColor
// TTFT display is gated to internal builds — apiMetricsRef was removed from
// props during a refactor, so skip this until it's re-threaded.
let ttftText: string | null = null
// When leader is idle but teammates are running (and we're viewing the leader),
// show a static dim idle display instead of the animated spinner — otherwise
// useStalledAnimation detects no new tokens after 3s and turns the spinner red.
if (leaderIsIdle && hasRunningTeammates && !foregroundedTeammate) {
return (
<Box flexDirection="column" width="100%" alignItems="flex-start">
<Box flexDirection="row" flexWrap="wrap" marginTop={1} width="100%">
<Text dimColor>
{TEARDROP_ASTERISK} Idle
{!allIdle && ' · teammates running'}
</Text>
</Box>
{showSpinnerTree && (
<TeammateSpinnerTree
selectedIndex={selectedIPAgentIndex}
isInSelectionMode={viewSelectionMode === 'selecting-agent'}
allIdle={allIdle}
leaderTokenCount={leaderTokenCount}
leaderIdleText="Idle"
/>
)}
</Box>
)
}
// When viewing an idle teammate, show static idle display instead of animated spinner
if (foregroundedTeammate?.isIdle) {
const idleText = allIdle
? `${TEARDROP_ASTERISK} Worked for ${formatDuration(Date.now() - foregroundedTeammate.startTime)}`
: `${TEARDROP_ASTERISK} Idle`
return (
<Box flexDirection="column" width="100%" alignItems="flex-start">
<Box flexDirection="row" flexWrap="wrap" marginTop={1} width="100%">
<Text dimColor>{idleText}</Text>
</Box>
{showSpinnerTree && hasRunningTeammates && (
<TeammateSpinnerTree
selectedIndex={selectedIPAgentIndex}
isInSelectionMode={viewSelectionMode === 'selecting-agent'}
allIdle={allIdle}
leaderVerb={leaderIsIdle ? undefined : leaderVerb}
leaderIdleText={leaderIsIdle ? 'Idle' : undefined}
leaderTokenCount={leaderTokenCount}
/>
)}
</Box>
)
}
// Time-based tip overrides: coarse thresholds so a stale ref read (we're
// off the 50ms clock) is fine. Other triggers (mode change, setMessages)
// cause re-renders that refresh this in practice.
let contextTipsActive = false
const tipsEnabled = settings.spinnerTipsEnabled !== false
const showClearTip = tipsEnabled && elapsedSnapshot > 1_800_000
const showBtwTip =
tipsEnabled && elapsedSnapshot > 30_000 && !getGlobalConfig().btwUseCount
const effectiveTip = contextTipsActive
? undefined
: showClearTip && !nextTask
? 'Use /clear to start fresh when switching topics and free up context'
: showBtwTip && !nextTask
? "Use /btw to ask a quick side question without interrupting Claude's current work"
: spinnerTip
// Budget text (ant-only) — shown above the tip line
let budgetText: string | null = null
if (feature('TOKEN_BUDGET')) {
const budget = getCurrentTurnTokenBudget()
if (budget !== null && budget > 0) {
const tokens = getTurnOutputTokens()
if (tokens >= budget) {
budgetText = `Target: ${formatNumber(tokens)} used (${formatNumber(budget)} min ${figures.tick})`
} else {
const pct = Math.round((tokens / budget) * 100)
const remaining = budget - tokens
const rate =
elapsedSnapshot > 5000 && tokens >= 2000
? tokens / elapsedSnapshot
: 0
const eta =
rate > 0
? ` \u00B7 ~${formatDuration(remaining / rate, { mostSignificantOnly: true })}`
: ''
budgetText = `Target: ${formatNumber(tokens)} / ${formatNumber(budget)} (${pct}%)${eta}`
}
}
}
return (
<Box flexDirection="column" width="100%" alignItems="flex-start">
<SpinnerAnimationRow
mode={mode}
reducedMotion={reducedMotion}
hasActiveTools={hasActiveTools}
responseLengthRef={responseLengthRef}
message={message}
messageColor={messageColor}
shimmerColor={shimmerColor}
overrideColor={overrideColor}
loadingStartTimeRef={loadingStartTimeRef}
totalPausedMsRef={totalPausedMsRef}
pauseStartTimeRef={pauseStartTimeRef}
spinnerSuffix={spinnerSuffix}
verbose={verbose}
columns={columns}
hasRunningTeammates={hasRunningTeammates}
teammateTokens={teammateTokens}
foregroundedTeammate={foregroundedTeammate}
leaderIsIdle={leaderIsIdle}
thinkingStatus={thinkingStatus}
effortSuffix={effortSuffix}
/>
{showSpinnerTree && hasRunningTeammates ? (
<TeammateSpinnerTree
selectedIndex={selectedIPAgentIndex}
isInSelectionMode={viewSelectionMode === 'selecting-agent'}
allIdle={allIdle}
leaderVerb={leaderIsIdle ? undefined : leaderVerb}
leaderIdleText={leaderIsIdle ? 'Idle' : undefined}
leaderTokenCount={leaderTokenCount}
/>
) : showExpandedTodos && tasksV2 && tasksV2.length > 0 ? (
<Box width="100%" flexDirection="column">
<MessageResponse>
<TaskListV2 tasks={tasksV2} />
</MessageResponse>
</Box>
) : nextTask || effectiveTip || budgetText ? (
// IMPORTANT: we need this width="100%" to avoid an Ink bug where the
// tip gets duplicated over and over while the spinner is running if
// the terminal is very small. TODO: fix this in Ink.
<Box width="100%" flexDirection="column">
{budgetText && (
<MessageResponse>
<Text dimColor>{budgetText}</Text>
</MessageResponse>
)}
{(nextTask || effectiveTip) && (
<MessageResponse>
<Text dimColor>
{nextTask
? `Next: ${nextTask.subject}`
: `Tip: ${effectiveTip}`}
</Text>
</MessageResponse>
)}
</Box>
) : null}
</Box>
)
}
// Brief/assistant mode spinner: single status line. PromptInput drops its
// own marginTop when isBriefOnly is active, so this component owns the
// 2-row footprint between messages and input. Footprint is [blank, content]
// — one blank row above (breathing room under the messages list), spinner
// flush against the input bar. PromptInput's absolute-positioned
// Notifications overlay compensates with marginTop=-2 in brief mode
// (PromptInput.tsx:~2928) so it floats into the blank row above the
// spinner, not over the spinner content. Paired with BriefIdleStatus which
// keeps the same footprint when idle.
type BriefSpinnerProps = {
mode: SpinnerMode
overrideMessage?: string | null
}
function BriefSpinner({
mode,
overrideMessage,
}: BriefSpinnerProps): React.ReactNode {
const settings = useSettings()
const reducedMotion = settings.prefersReducedMotion ?? false
const [randomVerb] = useState(() => sample(getSpinnerVerbs()) ?? 'Working')
const verb = overrideMessage ?? randomVerb
const connStatus = useAppState(s => s.remoteConnectionStatus)
// Track CLI activity so OS/IDE "busy" indicators fire in brief mode too
useEffect(() => {
const operationId = 'spinner-' + mode
activityManager.startCLIActivity(operationId)
return () => {
activityManager.endCLIActivity(operationId)
}
}, [mode])
// Drive both dot cycle and shimmer from the shared clock. The viewport
// ref is unused — the spinner unmounts on turn end so viewport-based
// pausing isn't needed.
const [, time] = useAnimationFrame(reducedMotion ? null : 120)
// Local tasks + remote tasks are mutually exclusive (viewer mode has an
// empty local AppState.tasks; local mode has remoteBackgroundTaskCount=0).
// Summing avoids a mode branch.
const runningCount = useAppState(
s =>
count(Object.values(s.tasks), isBackgroundTask) +
s.remoteBackgroundTaskCount,
)
// Connection trouble overrides the verb — `claude assistant` is a pure viewer,
// nothing useful is happening while the WS is down.
const showConnWarning =
connStatus === 'reconnecting' || connStatus === 'disconnected'
const connText =
connStatus === 'reconnecting' ? 'Reconnecting' : 'Disconnected'
// Dots padded to a fixed 3 columns so the right-aligned count doesn't
// jitter as the cycle advances.
const dotFrame = Math.floor(time / 300) % 3
const dots = reducedMotion ? '… ' : '.'.repeat(dotFrame + 1).padEnd(3)
// Shimmer: reverse-sweep highlight across the verb. Skip for connection
// warnings (shimmer reads as "working"; Reconnecting/Disconnected is not).
const verbWidth = useMemo(() => stringWidth(verb), [verb])
const glimmerIndex =
reducedMotion || showConnWarning
? -100
: computeGlimmerIndex(Math.floor(time / SHIMMER_INTERVAL_MS), verbWidth)
const { before, shimmer, after } = computeShimmerSegments(verb, glimmerIndex)
const { columns } = useTerminalSize()
const rightText = runningCount > 0 ? `${runningCount} in background` : ''
// Manual right-align via space padding — flexGrow spacers inside
// FullscreenLayout's `main` slot don't resolve a width and caused the
// diff engine to miss dot-frame updates.
const leftWidth = (showConnWarning ? stringWidth(connText) : verbWidth) + 3
const pad = Math.max(1, columns - 2 - leftWidth - stringWidth(rightText))
return (
<Box flexDirection="row" width="100%" marginTop={1} paddingLeft={2}>
{showConnWarning ? (
<Text color="error">{connText + dots}</Text>
) : (
<>
{before ? <Text dimColor>{before}</Text> : null}
{shimmer ? <Text>{shimmer}</Text> : null}
{after ? <Text dimColor>{after}</Text> : null}
<Text dimColor>{dots}</Text>
</>
)}
{rightText ? (
<>
<Text>{' '.repeat(pad)}</Text>
<Text color="subtle">{rightText}</Text>
</>
) : null}
</Box>
)
}
// Idle placeholder for brief mode. Same 2-row [blank, content] footprint
// as BriefSpinner so the input bar never jumps when toggling between
// working/idle/disconnected. See BriefSpinner's comment for the
// Notifications overlay coupling.
export function BriefIdleStatus(): React.ReactNode {
const connStatus = useAppState(s => s.remoteConnectionStatus)
const runningCount = useAppState(
s =>
count(Object.values(s.tasks), isBackgroundTask) +
s.remoteBackgroundTaskCount,
)
const { columns } = useTerminalSize()
const showConnWarning =
connStatus === 'reconnecting' || connStatus === 'disconnected'
const connText =
connStatus === 'reconnecting' ? 'Reconnecting…' : 'Disconnected'
const leftText = showConnWarning ? connText : ''
const rightText = runningCount > 0 ? `${runningCount} in background` : ''
if (!leftText && !rightText) return <Box height={2} />
const pad = Math.max(
1,
columns - 2 - stringWidth(leftText) - stringWidth(rightText),
)
return (
<Box marginTop={1} paddingLeft={2}>
<Text>
{leftText ? <Text color="error">{leftText}</Text> : null}
{rightText ? (
<>
<Text>{' '.repeat(pad)}</Text>
<Text color="subtle">{rightText}</Text>
</>
) : null}
</Text>
</Box>
)
}
export function Spinner(): React.ReactNode {
const settings = useSettings()
const reducedMotion = settings.prefersReducedMotion ?? false
const [ref, time] = useAnimationFrame(reducedMotion ? null : 120)
// Reduced motion: static dot instead of animated spinner
if (reducedMotion) {
return (
<Box ref={ref} flexWrap="wrap" height={1} width={2}>
<Text color="text"></Text>
</Box>
)
}
// Derive frame from synced time - all spinners animate together
const frame = Math.floor(time / 120) % SPINNER_FRAMES.length
return (
<Box ref={ref} flexWrap="wrap" height={1} width={2}>
<Text color="text">{SPINNER_FRAMES[frame]}</Text>
</Box>
)
}
function findNextPendingTask(tasks: Task[] | undefined): Task | undefined {
if (!tasks) {
return undefined
}
const pendingTasks = tasks.filter(t => t.status === 'pending')
if (pendingTasks.length === 0) {
return undefined
}
const unresolvedIds = new Set(
tasks.filter(t => t.status !== 'completed').map(t => t.id),
)
return (
pendingTasks.find(t => !t.blockedBy.some(id => unresolvedIds.has(id))) ??
pendingTasks[0]
)
}