Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 | 6x 6x 1x 6x 6x 4x 2x 1x 1x 12x 2x 12x 6x 12x 2x 2x 2x 2x 2x 6x 2x 2x 2x 2x 5x 5x 5x 5x 5x 4x 1x 1x 5x 4x 2x 4x 4x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 13x 5x 5x 5x 5x 5x 5x 6x 5x 1x 5x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x 4x 4x 4x 1x 1x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x | /**
* Ink-based skill runner with real-time progress display.
*
* While skills run, the dynamic Ink area shows running skills and active files.
* After Ink unmounts, the full per-skill + per-file breakdown is printed to
* stderr, followed by the normal findings report.
*
* UI updates are batched via setImmediate() to prevent rapid consecutive
* rerender() calls from producing duplicate output lines.
*
* Reporter spec: specs/reporters.md
* Terminal output design guide: specs/terminal-output.md
*/
import React, { useState, useEffect } from 'react';
import { render, Box, Text, Static } from 'ink';
import chalk from 'chalk';
import {
composeTasksWithFailFast,
runComposedSkillTasks,
type SkillTaskOptions,
type SkillTaskResult,
type RunTasksOptions,
type SkillProgressCallbacks,
type SkillState,
type FileState,
} from './tasks.js';
import { formatDuration, formatCost, truncate, countBySeverity, formatSeverityDot, pluralize, totalAuxiliaryCost } from './formatters.js';
import { Semaphore } from '../../utils/index.js';
import { Verbosity } from './verbosity.js';
import { ICON_CHECK, ICON_SKIPPED, ICON_PENDING, ICON_ERROR, SPINNER_FRAMES } from './icons.js';
import figures from 'figures';
import type { Finding, SkillReport } from '../../types/index.js';
import { ProviderFailureCircuitBreaker } from '../../sdk/circuit-breaker.js';
import { findingAppliesToFile } from '../../sdk/report-files.js';
interface SkillRunnerProps {
skills: SkillState[];
warnings: string[];
interrupted: boolean;
failFastTriggered: boolean;
}
function Spinner(): React.ReactElement {
const [frame, setFrame] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setFrame((f) => (f + 1) % SPINNER_FRAMES.length);
}, 80);
return () => clearInterval(timer);
}, []);
return <Text color="yellow">{SPINNER_FRAMES[frame]}</Text>;
}
function FileProgress({ file }: { file: FileState }): React.ReactElement {
const filename = truncate(file.filename, 50);
return (
<Box>
<Spinner />
<Text> {filename} [{file.currentHunk}/{file.totalHunks}]</Text>
</Box>
);
}
export function getSkillCostUSD(skill: SkillState): number | undefined {
const hasFileUsage = skill.files.some((file) => file.usage !== undefined);
const primaryCost = skill.usage?.costUSD
?? (hasFileUsage ? skill.files.reduce((sum, file) => sum + (file.usage?.costUSD ?? 0), 0) : undefined);
const auxiliaryCost = skill.auxiliaryUsage ? totalAuxiliaryCost(skill.auxiliaryUsage) : 0;
if (primaryCost === undefined && auxiliaryCost === 0) {
return undefined;
}
return (primaryCost ?? 0) + auxiliaryCost;
}
function RunningSkill({ skill }: { skill: SkillState }): React.ReactElement {
const activeFiles = skill.files.filter((f) => f.status === 'running');
const doneCount = skill.files.filter((f) => f.status === 'done' || f.status === 'skipped').length;
const totalCount = skill.files.length;
const findingCount = skill.files.reduce((sum, f) => sum + f.findings.length, 0);
const cost = getSkillCostUSD(skill);
return (
<Box flexDirection="column">
<Box>
<Spinner />
<Text> {skill.displayName}</Text>
{totalCount > 0 && <Text dimColor> [{doneCount}/{totalCount} files]</Text>}
{findingCount > 0 && <Text> {findingCount} {findingCount === 1 ? 'finding' : 'findings'}</Text>}
{cost !== undefined && cost > 0 && <Text dimColor> {formatCost(cost)}</Text>}
</Box>
{activeFiles.map((file) => (
<Box key={file.filename} marginLeft={2}>
<FileProgress file={file} />
</Box>
))}
</Box>
);
}
function CompletedSkill({ skill }: { skill: SkillState }): React.ReactElement {
if (skill.status === 'skipped') {
return (
<Text>
<Text color="yellow">{ICON_SKIPPED}</Text> {skill.displayName} <Text dimColor>[skipped]</Text>
</Text>
);
}
const findingCount = skill.findings.length;
const cost = getSkillCostUSD(skill);
const duration = skill.durationMs ? formatDuration(skill.durationMs) : undefined;
if (skill.status === 'error') {
return (
<Text>
<Text color="red">{ICON_ERROR}</Text> {skill.displayName}
{duration && <Text dimColor> [{duration}]</Text>}
</Text>
);
}
return (
<Text>
<Text color="green">{ICON_CHECK}</Text> {skill.displayName}
{duration && <Text dimColor> [{duration}]</Text>}
{findingCount > 0 && <Text> {findingCount} {findingCount === 1 ? 'finding' : 'findings'}</Text>}
{cost !== undefined && cost > 0 && <Text dimColor> {formatCost(cost)}</Text>}
</Text>
);
}
function SkillRunner({ skills, warnings, interrupted, failFastTriggered }: SkillRunnerProps): React.ReactElement {
const completed = skills.filter((s) => s.status === 'done' || s.status === 'skipped' || s.status === 'error');
const running = skills.filter((s) => s.status === 'running');
const pending = skills.filter((s) => s.status === 'pending');
return (
<Box flexDirection="column">
<Static items={warnings}>
{(warning, index) => (
<Text key={index}>{warning}</Text>
)}
</Static>
{completed.map((skill) => (
<CompletedSkill key={skill.name} skill={skill} />
))}
{running.map((skill) => (
<RunningSkill key={skill.name} skill={skill} />
))}
{pending.map((skill) => (
<Text key={skill.name} dimColor>
{ICON_PENDING} {skill.displayName}
</Text>
))}
{failFastTriggered && (
<Text color="yellow" dimColor>
{figures.warning} Stopping {'\u2014'} finding detected (--fail-fast)
</Text>
)}
{interrupted && !failFastTriggered && (
<Text color="yellow" dimColor>
{figures.warning} Interrupted, finishing up... (press Ctrl+C again to force exit)
</Text>
)}
</Box>
);
}
/** Create a terminal skill state for skills that were skipped or errored before starting. */
function makeTerminalSkillState(
tasks: SkillTaskOptions[],
name: string,
overrides: Partial<SkillState>
): SkillState {
const task = tasks.find((t) => t.name === name);
return {
name,
displayName: task?.displayName ?? name,
status: 'pending',
files: [],
findings: [],
...overrides,
};
}
/** No-op callbacks for quiet mode. */
const noop = (): void => {
return;
};
const noopCallbacks: SkillProgressCallbacks = {
onSkillStart: noop,
onSkillUpdate: noop,
onFileUpdate: noop,
onChunkComplete: noop,
onSkillComplete: noop,
onSkillSkipped: noop,
onSkillError: noop,
};
function syncFileFindingsWithFinalReport(files: FileState[], findings: Finding[]): FileState[] {
return files.map((file) => ({
...file,
findings: findings.filter((finding) => findingAppliesToFile(finding, file.filename)),
}));
}
/** Severity levels in display order. */
const SEVERITY_LEVELS = ['high', 'medium', 'low'] as const;
/** Print the per-file line within a skill summary. */
function printFileSummary(file: FileState): void {
Eif (file.status === 'done') {
const filename = truncate(file.filename, 50);
const counts = countBySeverity(file.findings);
let line = ` ${chalk.green(ICON_CHECK)} ${filename} ${chalk.dim(`[${file.totalHunks}/${file.totalHunks}]`)}`;
const severityParts = SEVERITY_LEVELS
.filter((s) => counts[s] > 0)
.map((s) => `${formatSeverityDot(s)} ${counts[s]}`);
Iif (severityParts.length > 0) line += ` ${severityParts.join(' ')}`;
Iif (file.durationMs !== undefined) line += chalk.dim(` ${formatDuration(file.durationMs)}`);
Iif (file.usage !== undefined) line += chalk.dim(` ${formatCost(file.usage.costUSD)}`);
process.stderr.write(`${line}\n`);
}
}
/** Print the full skill + file breakdown to stderr after Ink unmounts. */
function printSkillSummary(skillStates: SkillState[]): void {
for (const skill of skillStates) {
const duration = skill.durationMs ? chalk.dim(` [${formatDuration(skill.durationMs)}]`) : '';
const cost = getSkillCostUSD(skill);
const costText = cost !== undefined && cost > 0 ? chalk.dim(` ${formatCost(cost)}`) : '';
if (skill.status === 'done') {
process.stderr.write(`${chalk.green(ICON_CHECK)} ${skill.displayName}${duration}${costText}\n`);
} else if (skill.status === 'skipped') {
process.stderr.write(`${chalk.yellow(ICON_SKIPPED)} ${skill.displayName} ${chalk.dim('[skipped]')}\n`);
E} else if (skill.status === 'error') {
process.stderr.write(`${chalk.red(ICON_ERROR)} ${skill.displayName}${duration}\n`);
if (skill.error) {
process.stderr.write(`${chalk.red(` Error: ${skill.error}`)}\n`);
}
}
if (skill.status === 'done' || skill.status === 'error') {
for (const file of skill.files) {
printFileSummary(file);
}
const skippedCount = skill.files.filter((f) => f.status === 'skipped').length;
Iif (skippedCount > 0) {
process.stderr.write(` ${chalk.dim(`${skippedCount} ${pluralize(skippedCount, 'file')} skipped`)}\n`);
}
}
}
}
/**
* Run skill tasks with Ink-based real-time progress display.
*/
export async function runSkillTasksWithInk(
tasks: SkillTaskOptions[],
options: RunTasksOptions
): Promise<SkillTaskResult[]> {
const { verbosity, concurrency, failFastController, onSkillComplete: streamHook, onChunkComplete } = options;
const fireStreamHook = streamHook
? (report: SkillReport) => {
try { streamHook(report); } catch { /* streaming hook must not break the run */ }
}
: undefined;
if (tasks.length === 0 || verbosity === Verbosity.Quiet) {
// No tasks or quiet mode - run without UI using global semaphore.
const semaphore = new Semaphore(concurrency);
const circuitAbortController = new AbortController();
const circuitBreaker = new ProviderFailureCircuitBreaker({ abortController: circuitAbortController });
const composedTasks = composeTasksWithFailFast(
tasks,
failFastController,
circuitBreaker,
circuitAbortController,
);
const callbacks: SkillProgressCallbacks = {
...noopCallbacks,
...(fireStreamHook || failFastController
? {
onSkillComplete: (name: string, report) => {
noopCallbacks.onSkillComplete(name, report);
fireStreamHook?.(report);
Iif (failFastController && report.findings.length > 0) {
failFastController.abort();
}
},
}
: {}),
...(onChunkComplete
? {
onChunkComplete: (name, chunk) => {
noopCallbacks.onChunkComplete?.(name, chunk);
try { onChunkComplete(name, chunk); } catch { /* streaming hook must not break the run */ }
},
}
: {}),
};
return runComposedSkillTasks(composedTasks, callbacks, semaphore);
}
// Track skill states
const skillStates: SkillState[] = [];
// Warnings are rendered via Ink's Static component so they appear above the
// dynamic spinner area without corrupting it.
const warnings: string[] = [];
// Track interrupt state for rendering in the Ink component
let interrupted = false;
let failFastTriggered = false;
process.stderr.write(`${chalk.bold('SKILLS')}\n`);
// Create Ink instance
const { rerender, unmount, clear } = render(
<SkillRunner skills={skillStates} warnings={[]} interrupted={false} failFastTriggered={false} />,
{ stdout: process.stderr }
);
// Batch UI updates to prevent rapid consecutive rerenders that cause duplicate lines.
// Without batching, multiple callbacks firing in quick succession (e.g., 5 files
// starting simultaneously) trigger 5 immediate rerenders, which Ink cannot
// process correctly, resulting in the same line appearing multiple times.
let updatePending = false;
let unmounted = false;
const updateUI = () => {
if (updatePending || unmounted) return;
updatePending = true;
setImmediate(() => {
updatePending = false;
Iif (unmounted) return;
rerender(<SkillRunner skills={[...skillStates]} warnings={[...warnings]} interrupted={interrupted} failFastTriggered={failFastTriggered} />);
});
};
// Listen for abort signal to show interrupt message in the Ink UI
const abortSignal = tasks[0]?.runnerOptions?.abortController?.signal;
Iif (abortSignal && !abortSignal.aborted) {
abortSignal.addEventListener('abort', () => {
// Only show interrupt message for user SIGINT, not fail-fast
if (!failFastController?.signal.aborted) {
interrupted = true;
updateUI();
}
}, { once: true });
}
// Show fail-fast message when triggered
if (failFastController) {
failFastController.signal.addEventListener('abort', () => {
failFastTriggered = true;
updateUI();
}, { once: true });
}
// Callbacks to update state
const callbacks: SkillProgressCallbacks = {
onSkillStart: (skill) => {
skillStates.push(skill);
updateUI();
},
onSkillUpdate: (name, updates) => {
const idx = skillStates.findIndex((s) => s.name === name);
const existing = skillStates[idx];
Eif (idx >= 0 && existing) {
const next: SkillState = { ...existing, ...updates };
Eif (updates.findings !== undefined) {
next.files = syncFileFindingsWithFinalReport(next.files, updates.findings);
}
skillStates[idx] = next;
updateUI();
}
},
onFileUpdate: (skillName, filename, updates) => {
const skill = skillStates.find((s) => s.name === skillName);
Eif (skill) {
const file = skill.files.find((f) => f.filename === filename);
Eif (file) {
Object.assign(file, updates);
updateUI();
}
}
},
onSkillComplete: (name, report) => {
fireStreamHook?.(report);
const idx = skillStates.findIndex((s) => s.name === name);
const existing = skillStates[idx];
Eif (idx >= 0 && existing) {
skillStates[idx] = {
...existing,
status: existing.status === 'error' || existing.status === 'skipped' ? existing.status : 'done',
durationMs: report.durationMs,
findings: report.findings,
usage: report.usage,
auxiliaryUsage: report.auxiliaryUsage,
files: syncFileFindingsWithFinalReport(existing.files, report.findings),
};
}
Iif (failFastController && report.findings.length > 0) {
failFastController.abort();
}
updateUI();
},
onChunkComplete: (name, chunk) => {
try { onChunkComplete?.(name, chunk); } catch { /* streaming hook must not break the run */ }
},
onSkillSkipped: (name) => {
skillStates.push(makeTerminalSkillState(tasks, name, { status: 'skipped' }));
updateUI();
},
onSkillError: (name, error) => {
const idx = skillStates.findIndex((s) => s.name === name);
const existing = skillStates[idx];
if (idx >= 0 && existing) {
skillStates[idx] = { ...existing, status: 'error', error };
} else {
skillStates.push(makeTerminalSkillState(tasks, name, { status: 'error', error }));
}
updateUI();
},
onLargePrompt: (_skillName, filename, lineRange, chars, estimatedTokens) => {
const location = `${filename}:${lineRange}`;
const size = `${Math.round(chars / 1000)}k chars (~${Math.round(estimatedTokens / 1000)}k tokens)`;
warnings.push(`${chalk.yellow(figures.warning)} Large prompt for ${location}: ${size}`);
updateUI();
},
onPromptSize: verbosity >= Verbosity.Debug
? (_skillName, filename, lineRange, systemChars, userChars, totalChars, estimatedTokens) => {
const location = `${filename}:${lineRange}`;
warnings.push(chalk.dim(`[debug] Prompt for ${location}: system=${systemChars}, user=${userChars}, total=${totalChars} chars (~${estimatedTokens} tokens)`));
updateUI();
}
: undefined,
onHunkFailed: verbosity >= Verbosity.Verbose
? (_skillName, filename, lineRange, error) => {
const location = `${filename}:${lineRange}`;
warnings.push(`${chalk.yellow(figures.warning)} Chunk failed: ${location} ${chalk.dim(`\u2014 ${error}`)}`);
updateUI();
}
: undefined,
onExtractionFailure: verbosity >= Verbosity.Verbose
? (_skillName, filename, lineRange, error, preview) => {
const location = `${filename}:${lineRange}`;
warnings.push(`${chalk.yellow(figures.warning)} Extraction failed: ${location} ${chalk.dim(`\u2014 ${error}`)}`);
if (verbosity >= Verbosity.Debug && preview) {
warnings.push(chalk.dim(`[debug] Output preview: ${preview.slice(0, 200)}`));
}
updateUI();
}
: undefined,
onRetry: verbosity >= Verbosity.Verbose
? (_skillName, filename, lineRange, attempt, maxRetries, error, delayMs) => {
const location = `${filename}:${lineRange}`;
const retryInfo = `attempt ${attempt}/${maxRetries}`;
const delay = delayMs > 0 ? `, retrying in ${Math.round(delayMs / 1000)}s` : '';
warnings.push(chalk.dim(`[debug] Retry ${location} (${retryInfo}${delay}): ${error}`));
updateUI();
}
: undefined,
};
// Global semaphore gates file-level work across all skills.
const semaphore = new Semaphore(concurrency);
// Compose per-task abort controllers: fire on SIGINT, fail-fast, or provider circuit breaker.
const circuitAbortController = new AbortController();
const circuitBreaker = new ProviderFailureCircuitBreaker({ abortController: circuitAbortController });
const composedTasks = composeTasksWithFailFast(
tasks,
failFastController,
circuitBreaker,
circuitAbortController,
);
// Launch all skills in parallel; the semaphore is the sole concurrency gate.
const results = await runComposedSkillTasks(composedTasks, callbacks, semaphore);
// Flush any pending setImmediate from updateUI so last-tick warnings are
// rendered before we tear down. setImmediate is FIFO, so our callback runs
// after the queued rerender.
await new Promise((resolve) => setImmediate(resolve));
unmounted = true;
clear();
unmount();
printSkillSummary(skillStates);
return results;
}
|