SLOPSHOPPER

test-progress

Acompanha em segundo plano os testes dos módulos cadastrados no workspace, com contadores observados, estado e logs por módulo.

panebandguardcommandtoastprompt
v0.14.0MITupdated 2026-10-26fabiopbarbieri/claude-test-progress
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · test-progress
│ ┃ claude-test-progress ✕ › fix the failing auth test and add an audit log call │ ┃ 0/0/0 ? │ ┃ Nenhum módulo em .claude/test-progress.json ⏺ Read(src/auth.ts) │ ┃ Coletor retornou resposta inválida (exit 0); ⎿ Read 6 lines │ ┃ requer Node 14+ local. ⏺ Update(src/auth.ts) │ ┃ Registro: O comando test-progress está ⎿ Added 2 lines, removed 1 line │ ┃ indisponível ou pertence a outra origem. ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /test-progress │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · claude-test-progress
0/0/0 ? Nenhum módulo em .claude/test-progress.json Coletor retornou resposta inválida (exit 0); requer Node 14+ local. Registro: O comando test-progress está indisponível ou pertence a outra origem.
README

Claude Test Progress

Test Progress

Acompanhe suas suítes de teste no Claude Code enquanto elas rodam em segundo plano. Plugin test-progress, um Claude Code Mod independente da Anthropic. Versão 0.14.0, licença MIT.

Painel do Test Progress com sete módulos de projetos fictícios

  • Um painel para todas as suítes: Maven/JUnit, Karma/Angular, Playwright, pytest/unittest, RSpec, Rails/Minitest ou qualquer comando.
  • Progresso ao vivo: barra, percentual, ✓ passaram, ✗ falharam, ⊘ ignorados e tempo.
  • Ações no próprio painel: ▶ inicia, ■ cancela, ↻ Apenas com erro reexecuta só o que falhou e clicar no nome abre o log com as cores do runner.
  • Resumo acima do prompt: uma linha com o que está rodando e as falhas ainda não vistas.

O topo do painel conta módulos com sucesso / com erro / total. O percentual é testes resolvidos / total conhecido; ~ indica total parcial, que ainda pode crescer. 100% não comprova sucesso: confira estado, falhas e código de saída.

Instalar

Com acesso SSH ao GitHub configurado, rode no Claude Code um comando por vez (colados juntos, as linhas seguintes viram argumentos do primeiro):

/plugin marketplace add git@github.com:fabiopbarbieri/claude-test-progress.git
/plugin install test-progress@test-progress-marketplace
/reload-plugins

Depois, /test-progress help, /test-progress paths e /test-progress list. Instalação por terminal, clone SSH e --plugin-dir: guia de uso.

Configurar

O jeito mais simples é pedir ao Claude: a skill test-progress:configure cadastra as suítes do projeto e explica erros do painel. Depois, quando você pedir para rodar os testes, o Claude os inicia pelo coletor, para o run aparecer no painel: pela ferramenta mcp__test-progress__tests, que o Mod registra em cada sessão, ou pela skill test-progress:run-tests via Bash onde a ferramenta não alcança (subagente em outro diretório, claude -p sem o Mod). list, status e logs não pedem permissão; start e cancel seguem as suas regras de permissão para mcp__test-progress__tests e, sem regra, perguntam antes.

O cadastro fica em .claude/test-progress.json, no diretório em que você abriu a sessão. Exemplo para um app Maven com mvnw na raiz:

{
  "schemaVersion": 1,
  "modules": {
    "api": {
      "label": "API",
      "command": ["./mvnw", "test"],
      "cwd": ".",
      "adapter": "maven",
      "runtime": "inherit"
    }
  }
}

command é argv (um item por argumento, sem shell). Para contar testes em outras suítes, use os adapters pelo caminho absoluto mostrado em /test-progress paths. Exemplos prontos, templates pessoais e todos os campos: configurar seu projeto.

Comandos

ComandoAção
/test-progressAbre ou fecha o painel, sem iniciar testes
/test-progress listLista módulos e diagnósticos
/test-progress start <id> / start allInicia um módulo / todos os habilitados
/test-progress logs <id>Mostra o log do módulo
/test-progress cancel <id> / cancel allCancela a execução
/test-progress help / pathsAjuda / caminhos da instalação

Acrescente --text para a saída em texto. O autocomplete do prompt sugere as ações e os IDs cadastrados. A partir do Claude Code 2.1.300, o prompt mostra em cinza, depois do cursor, os módulos que uma ação aceita assim que ela é digitada (/test-progress start → api | web | all, cortada com …+N quando não cabe) ou o resto da única opção que o texto digitado já define; só o que foi digitado é enviado. No painel, ⇅ alterna a ordem dos módulos (cadastro, nome, recentes, atenção) e ? mostra a legenda.

Quando todas as execuções terminam e alguma falhou, o painel abre sozinho no log do primeiro módulo com falha, inclusive para execuções iniciadas pelo Claude via CLI. Ele não toma o teclado e, por ser aberto pelo mod, só aparece com o terminal largo o bastante (144 colunas); fechado, não reabre para as mesmas execuções.

No mesmo momento sai uma notificação nativa ("Falharam: API (1 ✗)") pelo canal de notificação configurado no Claude Code, para avisar mesmo longe do terminal ou enquanto o painel espera largura.

Atualizar ou remover

Encerre os jobs antes de trocar a instalação: fechar o painel, recarregar ou desinstalar não para processos em segundo plano.

claude plugin marketplace update test-progress-marketplace
claude plugin update test-progress@test-progress-marketplace --scope user

Para remover:

claude plugin uninstall test-progress@test-progress-marketplace --scope user

Depois de atualizar, confira /test-progress paths e ajuste os caminhos dos adapters. Procedimento completo.

Compatibilidade

Claude Code 2.1.296+ e Node 14+ para o coletor. Linux e WSL são o caminho principal; Windows nativo tem guia próprio. O plugin não instala runners, browsers nem runtimes. Versões testadas por suíte: compatibilidade.

Guias

Uso · Diagnóstico · Compatibilidade · Windows · Angular 9 · Validação · Extensões · Contribuição · CI e governança · Segurança · Licença MIT

Source 5 files
hooks/register.tsx 1032 lines
1// Claude Code Mods 2.1.296+. No host Node APIs run inside the Mod sandbox.
2import { atom, read } from 'claude-code';
3import type { EngineInterface, Register, Timer } from 'claude-code';
4import type { TestProgressDiagnostic, TestProgressPanel } from '../types';
5import { ACTIVE, labels, validateEnvelope, parseCommand, visibleModuleIds, moduleTitle, countSummary, diagnosticText,
6  sanitizeText, sanitizeTail, plainTail, ansiSpans, statusGlyph, progressBar, progressSvg, outcomeText, summaryCounts, finishedWithFailure, compactPercent, compactCounts, clock,
7  configStatus, SORTS, sortLabels, nextSort, sortModuleIds } from '../runner/module-presentation.mjs';
8
9type $ = EngineInterface;
10type Action = 'list' | 'start' | 'status' | 'logs' | 'cancel' | 'help' | 'paths';
11const PANE = 'claude-test-progress';
12const NARROW_COLUMNS = 60;
13// Columns the band leaves free at the right, where the host draws its collapse control.
14const BAND_RESERVE = 6;
15const IDLE_POLL_TICKS = 10;
16const LOG_ROWS = 12;
17const empty = (): TestProgressPanel => ({ identity: '', generation: 0, sessionOwner: '', modules: {}, jobs: {},
18  stateDiagnostics: {}, workspace: null, busy: false, lastError: '', registrationError: '', selectedLogs: null,
19  logTail: [], logTop: null, chooseLogs: false, showHelp: false, sort: 'order', seenRuns: [], collector: null });
20// The host holds what the pane draws, so a hot reload keeps the selection, the seen runs and the collector Node.
21const panel = atom({ plugin: 'test-progress', key: 'panel' } as const, empty());
22// Working copy: hooks change it, then publish it; drawings read the host's value and redraw when it changes.
23let p = empty(), hydrated = false, published = '';
24// Collector calls run one at a time; commands and buttons wait instead of being dropped.
25let queue: Promise<unknown> = Promise.resolve(), queued = 0, idleTicks = 0, timer: Timer | null = null;
26const errorText = (error: unknown) => String(error instanceof Error ? error.message : error);
27async function hydrate($: $) {
28  if (hydrated) return;
29  const held = await read($, panel);
30  if (!hydrated) {
31    p = { ...empty(), ...held, busy: false };
32    if (!SORTS.includes(p.sort)) p.sort = 'order';
33    hydrated = true; published = JSON.stringify(p);
34  }
35}
36async function publish($: $) {
37  hydrated = true;
38  const next = JSON.stringify(p);
39  if (next === published) return;
40  published = next;
41  await $.state.set({ plugin: 'test-progress', key: 'panel' }, JSON.parse(next) as TestProgressPanel);
42}
43const visible = () => visibleModuleIds(p.modules, p.jobs, p.stateDiagnostics);
44const enabled = () => visible().filter(id => p.modules[id]?.enabled);
45const catalogue = () => JSON.stringify({ modules: p.modules, moduleConfig: p.workspace?.moduleConfig,
46  stateBlocked: p.workspace?.stateBlocked, stateDiagnostics: p.stateDiagnostics });
47const actionProjection = () => JSON.stringify({ catalogue: catalogue(), jobs: Object.keys(p.jobs).sort().map(id => {
48  const job = p.jobs[id]!;
49  return [id, job.runId, job.status, !!job.recoveryRequired, !!job.cancellable];
50}) });
51// Labels alone read best; a label shared by two visible modules gets its ID.
52function displayNames() {
53  const ids = visible(), count: Record<string, number> = {};
54  for (const id of ids) { const label = p.modules[id]?.label ?? id; count[label] = (count[label] ?? 0) + 1; }
55  return Object.fromEntries(ids.map(id => {
56    const label = p.modules[id]?.label ?? id;
57    return [id, (count[label] ?? 0) > 1 && label !== id ? `${label} (${id})` : label];
58  }));
59}
60// The log shows a window of LOG_ROWS lines; with no top of its own it follows the end.
61function logWindow() {
62  const max = Math.max(0, p.logTail.length - LOG_ROWS);
63  return { top: p.logTop === null ? max : Math.min(Math.max(0, p.logTop), max), max };
64}
65const closeLogs = () => { p.selectedLogs = null; p.logTail = []; p.logTop = null; };
66const diagnostics = (id: string): TestProgressDiagnostic[] => [...(p.modules[id]?.diagnostics ?? []), ...(p.stateDiagnostics[id] ?? [])];
67function serialized<T>(task: () => Promise<T>): Promise<T> {
68  queued += 1;
69  const run = queue.then(task).finally(() => { queued -= 1; });
70  queue = run.catch(() => {});
71  return run;
72}
73const liveJobs = () => Object.values(p.jobs).some(job => ACTIVE.has(job.status) || job.recoveryRequired);
74// Idle, a query starts a Node only when something it read changed. Each answer names its sources
75// (the state directory and the configuration files and module folders); every IDLE_CHECK_TICKS
76// seconds the Mod compares them through the host's file system, with a query at least every
77// IDLE_REFRESH_TICKS seconds (ten after a failed one). Without sources, or if the file system
78// refuses, the panel polls every IDLE_POLL_TICKS seconds instead.
79const IDLE_CHECK_TICKS = 2;
80const IDLE_REFRESH_TICKS = 300;
81const absolutePath = (value: unknown): value is string => typeof value === 'string' && !value.includes('\0') &&
82  (value.startsWith('/') || /^[a-z]:\\/i.test(value));
83let sources: { identity: string; state: string; paths: string[] } | null = null;
84let baseline: string | null = null, refreshTicks = 0;
85function rememberSources(value: { state?: unknown; paths?: unknown } | undefined) {
86  const paths = Array.isArray(value?.paths) ? value.paths : null;
87  sources = absolutePath(value?.state) && paths && paths.length <= 256 && paths.every(absolutePath)
88    ? { identity: p.identity, state: value.state, paths } : null;
89}
90async function fingerprint($: $) {
91  const current = sources;
92  if (!current || current.identity !== p.identity) return null;
93  try {
94    const rows = (await $.fs.list(current.state)).map(entry => `${entry.name}|${entry.kind}|${entry.size}|${entry.mtimeMs}`).sort();
95    for (const path of current.paths) {
96      const info = await $.fs.stat(path).catch(() => null);
97      // A folder counts by presence: its own time moves with every file a test writes in it.
98      rows.push(`${path}|${!info ? 'absent' : info.kind === 'dir' ? 'dir' : `${info.kind}|${info.size}|${info.mtimeMs}`}`);
99    }
100    return rows.join('\n');
101  } catch { return null; }
102}
103// Poll every second only while something can change without us: an unseen identity or a live job.
104async function pollDue($: $) {
105  if (!p.workspace || liveJobs()) { idleTicks = 0; return true; }
106  const ticks = ++idleTicks, refresh = --refreshTicks <= 0;
107  if (!refresh && ticks % IDLE_CHECK_TICKS) return false;
108  const print = refresh ? null : await fingerprint($);
109  const due = refresh || (print === null ? ticks >= IDLE_POLL_TICKS : print !== baseline);
110  if (due) idleTicks = 0;
111  return due;
112}
113// While a job is live, one collector started once streams each status change (`watch`),
114// instead of a Node started every second. A watcher that stops answering, or one the host
115// cannot start, falls back to the per-second query.
116const WATCH_STALE_MS = 5000;
117const WATCH_RETRY_MS = 60000;
118type Watcher = { identity: string; logs: string; seenAt: number; stop: () => void };
119let watcher: Watcher | null = null, watchBlockedUntil = 0;
120function stopWatcher() {
121  const current = watcher;
122  watcher = null;
123  current?.stop();
124}
125function applyEnvelope(data: ReturnType<typeof validateEnvelope>) {
126  p.modules = data.modules; p.jobs = data.jobs; p.workspace = data.workspace; p.stateDiagnostics = data.stateDiagnostics;
127  rememberSources(data.sources);
128  const selected = p.selectedLogs && p.jobs[p.selectedLogs.id];
129  if (p.selectedLogs && selected?.runId === p.selectedLogs.runId && Array.isArray(selected.logTail)) p.logTail = sanitizeTail(selected.logTail);
130}
131async function applyWatched($: $, self: Watcher, line: string) {
132  if (watcher !== self) return;
133  await synchronizeIdentity($);
134  if (p.identity !== self.identity) { stopWatcher(); return; }
135  let data;
136  try { data = validateEnvelope(JSON.parse(line)); } catch { return; }
137  applyEnvelope(data);
138  p.lastError = data.ok ? '' : data.error ?? 'O coletor encerrou a observação.';
139  if (await paneShown($)) acknowledge();
140  else await autoOpen($);
141  await publish($);
142}
143// True while a watcher for this identity and log selection runs or was just started.
144function watch($: $, logs: string) {
145  const direct = p.collector?.identity === p.identity ? p.collector : null;
146  if (!direct || Date.now() < watchBlockedUntil) return false;
147  if (watcher?.identity === p.identity && watcher.logs === logs) return true;
148  stopWatcher();
149  const [cwd = '', owner = ''] = p.identity.split('\n');
150  let stream: ReturnType<$['process']['spawn']>;
151  try {
152    // A 1 MB young generation keeps this long-lived Node small (LONG_LIVED_NODE_FLAGS).
153    stream = $.process.spawn({ argv: [direct.path, '--max-semi-space-size=1', `${$.plugin.root}/runner/cli.mjs`, 'watch',
154      '--cwd', cwd, '--owner', owner, '--module', logs], env: { TEST_PROGRESS_NODE_SOURCE: direct.source } });
155  } catch { watchBlockedUntil = Date.now() + WATCH_RETRY_MS; return false; }
156  const self: Watcher = { identity: p.identity, logs, seenAt: Date.now(),
157    stop: () => { void stream.return({ code: null, signal: null }).catch(() => {}); } };
158  watcher = self;
159  void (async () => {
160    let buffer = '', lines = 0;
161    try {
162      for await (const chunk of stream) {
163        if (watcher !== self) break;
164        if (chunk.stream !== 'stdout') continue;
165        buffer += chunk.text;
166        for (let end = buffer.indexOf('\n'); end >= 0; end = buffer.indexOf('\n')) {
167          const line = buffer.slice(0, end);
168          buffer = buffer.slice(end + 1);
169          if (!line.trim()) continue;
170          lines++; self.seenAt = Date.now();
171          await serialized(() => applyWatched($, self, line));
172        }
173      }
174    } catch { /* The per-second query takes over. */ }
175    finally {
176      if (watcher === self) watcher = null;
177      if (!lines) watchBlockedUntil = Date.now() + WATCH_RETRY_MS;
178    }
179  })();
180  return true;
181}
182const validCollector = (value: { path?: unknown; source?: unknown } | undefined): value is { path: string; source: string } =>
183  typeof value?.path === 'string' && !value.path.includes('\0') && (value.path.startsWith('/') || /^[a-z]:\\/i.test(value.path)) &&
184  typeof value.source === 'string' && /^[\w-]{1,32}$/.test(value.source);
185// The bootstrap's Node is kept between sessions for the same folder, PATH and override, so a new
186// session queries it directly instead of starting PowerShell or bash first. A Node that no longer
187// answers is forgotten, and that query goes through the bootstrap.
188const COLLECTORS = 'collectors';
189async function collectorKey($: $, cwd: string) {
190  try {
191    const [path, override] = await Promise.all([$.env.get('PATH').then(value => value ?? $.env.get('Path')), $.env.get('TEST_PROGRESS_NODE')]);
192    return JSON.stringify([cwd, path ?? null, override ?? null]);
193  } catch { return null; }
194}
195async function storedCollectors($: $) {
196  const value = await $.store.get(COLLECTORS).catch(() => undefined);
197  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, { path?: unknown; source?: unknown }> : {};
198}
199async function rememberedCollector($: $, key: string | null) {
200  if (!key) return null;
201  const value = (await storedCollectors($))[key];
202  if (!validCollector(value)) return null;
203  p.collector = { identity: p.identity, path: value.path, source: value.source };
204  return p.collector;
205}
206async function keepCollector($: $, key: string | null, value: { path: string; source: string }) {
207  if (!key) return;
208  // The newest 32 folders stay; each entry is a path and a source label.
209  const kept = Object.entries(await storedCollectors($)).filter(([entry]) => entry !== key).slice(-31);
210  await $.store.set(COLLECTORS, Object.fromEntries([...kept, [key, { path: value.path, source: value.source }]])).catch(() => {});
211}
212async function forgetCollector($: $, key: string | null) {
213  if (!key) return;
214  const all = await storedCollectors($);
215  if (!(key in all)) return;
216  delete all[key];
217  await $.store.set(COLLECTORS, all).catch(() => {});
218}
219const duration = (ms: number | undefined) => typeof ms === 'number' ? `${Math.floor(ms / 1000)}s` : 'desconhecida';
220function startAllowed(id: string) {
221  const job = p.jobs[id];
222  return !p.busy && p.workspace?.moduleConfig?.status === 'valid' && !p.workspace?.stateBlocked &&
223    !p.stateDiagnostics['*']?.length && p.modules[id]?.enabled === true && p.modules[id]?.directoryPresent === true &&
224    !diagnostics(id).length && !(job && ACTIVE.has(job.status)) && !job?.recoveryRequired;
225}
226const allAllowed = () => enabled().length > 0 && enabled().every(startAllowed);
227const failedIds = () => enabled().filter(id => finishedWithFailure(p.jobs[id]));
228const failedAllowed = () => failedIds().length > 0 && failedIds().every(startAllowed);
229// Opening or using the pane acknowledges the runs it shows, so the band can step aside.
230function acknowledge() {
231  const seen = new Set(p.seenRuns);
232  for (const job of Object.values(p.jobs)) seen.add(job.runId);
233  if (seen.size !== p.seenRuns.length) p.seenRuns = [...seen].slice(-200);
234}
235function shortSummary(id: string) {
236  const job = p.jobs[id];
237  if (!job) return `${moduleTitle(id, p.modules[id])}: sem execução`;
238  const counts = compactCounts(job).map(count => count.text).join(' ');
239  return `${moduleTitle(id, p.modules[id])}: ${statusGlyph(job).glyph} ${compactPercent(job)} · ${labels[job.status] ?? job.status}${counts ? ` · ${counts}` : ''}`;
240}
241function textSummary() {
242  const rows = ['Test Progress', ...(p.sessionOwner ? [`owner=${p.sessionOwner}`] : [])];
243  for (const id of visible()) {
244    const job = p.jobs[id];
245    rows.push(shortSummary(id), `  linguagem=${p.modules[id]?.language ?? 'não informada'}`);
246    if (!p.modules[id]?.enabled) rows.push('  Módulo removido/desativado.');
247    for (const item of diagnostics(id)) rows.push(`  Diagnóstico: ${diagnosticText(item)}`);
248    if (!job) continue;
249    rows.push(`  ${countSummary(job)}; passed=${job.passed ?? 0}, failed=${job.failed ?? 0}, skipped=${job.skipped ?? 0}`,
250      `  origem=${job.source}; fase=${job.phase}; exitCode=${job.exitCode ?? 'ainda desconhecido'}`,
251      `  duração=${duration(job.elapsedMs)}; último sinal do executor=${job.heartbeatAt ?? 'ainda não observado'}`,
252      `  última saída=${job.lastOutputAt ?? 'não observada'}; último progresso reconhecido=${job.lastProgressAt ?? 'não observado'}`,
253      `  runId=${job.runId}; log=${job.logPath ?? 'não disponível'}`);
254    if (job.collectorRuntime) rows.push(`  Node coletor=${job.collectorRuntime.version} (${job.collectorRuntime.source})`);
255    if (job.nodeRuntime) rows.push(`  Node da suíte=${job.nodeRuntime.version} (${job.nodeRuntime.source}); .nvmrc=${job.nodeRuntime.nvmrc ?? 'ausente'}`);
256    if (job.error) rows.push(`  ${job.error}`);
257  }
258  if (!visible().length) rows.push('Nenhum módulo ativado neste workspace.', 'Configure .claude/test-progress.json; consulte /test-progress help.');
259  rows.push(`Cadastro: ${configStatus[p.workspace?.moduleConfig?.status ?? ''] ?? 'não consultado'} · .claude/test-progress.json`);
260  if (p.workspace?.error) rows.push(`Configuração: ${p.workspace.error}`);
261  for (const item of p.workspace?.moduleConfig?.diagnostics ?? []) rows.push(`Configuração: ${diagnosticText(item)}`);
262  for (const item of p.stateDiagnostics['*'] ?? []) rows.push(`Estado: ${diagnosticText(item)}`);
263  if (p.lastError) rows.push(`Erro: ${p.lastError}`);
264  if (p.registrationError) rows.push(`Registro: ${p.registrationError}`);
265  return rows.join('\n');
266}
267async function synchronizeIdentity($: $) {
268  await hydrate($);
269  const cwd = await $.session.cwd(), owner = await $.session.id();
270  const key = `${cwd}\n${owner}`;
271  if (p.identity !== key) {
272    // A new identity starts clean, but the collector Node it bootstrapped, the registration outcome and the ordering stay.
273    p = { ...empty(), identity: key, generation: p.generation + 1, sessionOwner: owner,
274      registrationError: p.registrationError, collector: p.collector, busy: p.busy, sort: p.sort };
275  }
276  return { cwd, owner, generation: p.generation };
277}
278async function collect($: $, action: Action = 'status', moduleId = 'all'): Promise<unknown> {
279  const context = await synchronizeIdentity($);
280  const windows = /^[a-z]:[\\/]|^\\\\/i.test(context.cwd);
281  // After one bootstrap, call the Node it selected directly: no shell, no PATH/nvm probing.
282  let key: string | null | undefined;
283  const keyOf = async () => key === undefined ? (key = await collectorKey($, context.cwd)) : key;
284  const direct = p.collector?.identity === p.identity ? p.collector : await rememberedCollector($, await keyOf());
285  // What the files looked like before this query; an answer makes it the idle baseline.
286  const print = await fingerprint($);
287  const settle = (ok: boolean) => { baseline = print; refreshTicks = ok ? IDLE_REFRESH_TICKS : IDLE_POLL_TICKS; };
288  let argv: string[];
289  if (direct) argv = [direct.path, `${$.plugin.root}/runner/cli.mjs`, action,
290    '--cwd', context.cwd, '--owner', context.owner, '--module', moduleId];
291  else if (windows) {
292    const override = await $.env.get('TEST_PROGRESS_POWERSHELL'), systemRoot = await $.env.get('SystemRoot');
293    argv = [override || (systemRoot ? `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : 'powershell.exe'),
294      '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', `${$.plugin.root}/scripts/run-collector.ps1`,
295      '-Action', action, '-Cwd', context.cwd, '-Owner', context.owner, '-Module', moduleId];
296  } else argv = ['bash', `${$.plugin.root}/scripts/run-collector.sh`, action,
297    '--cwd', context.cwd, '--owner', context.owner, '--module', moduleId];
298  const init = { timeoutMs: action === 'start' ? 60000 : windows ? 15000 : 5000,
299    ...(direct ? { env: { TEST_PROGRESS_NODE_SOURCE: direct.source } } : {}) };
300  // A stale cached Node falls back to the bootstrap once; a start is never repeated.
301  const fallback = async () => { p.collector = null; await forgetCollector($, await keyOf()); return !!direct && action !== 'start'; };
302  const changed = () => new Error('A sessão mudou durante a consulta. Atualize para ver os jobs desta sessão.');
303  let response;
304  try { response = await $.process.run(argv, init); }
305  catch (error) {
306    await synchronizeIdentity($);
307    if (context.generation !== p.generation) throw changed();
308    if (direct && await fallback()) return collect($, action, moduleId);
309    settle(false);
310    throw error;
311  }
312  await synchronizeIdentity($);
313  if (context.generation !== p.generation) throw changed();
314  let raw: unknown;
315  try { raw = JSON.parse(response.stdout.trim()); }
316  catch {
317    if (direct && await fallback()) return collect($, action, moduleId);
318    settle(false);
319    throw new Error(sanitizeText(response.stderr).trim().slice(0, 1024) || `Coletor retornou resposta inválida (exit ${response.exitCode}); requer Node 14+ local.`);
320  }
321  let data;
322  try { data = validateEnvelope(raw); } catch (error) { settle(false); throw error; }
323  if (!direct && validCollector(data.collector)) {
324    p.collector = { identity: p.identity, path: data.collector.path, source: data.collector.source };
325    await keepCollector($, await keyOf(), p.collector);
326  }
327  // Error envelopes still carry the valid catalogue and persistent jobs.
328  applyEnvelope(data);
329  settle(data.ok && response.exitCode === 0);
330  if (!data.ok || response.exitCode !== 0) {
331    const actionErrors = Object.entries(data.actionResults ?? {}).filter(([, result]) => !result.ok)
332      .map(([id, result]) => `${id}: ${result.error ?? 'ação recusada'}`).join('\n');
333    // The envelope rides along: the model tool answers with it, catalogue and diagnostics included.
334    throw Object.assign(new Error(data.error ?? (actionErrors || `Coletor encerrou com código ${response.exitCode}.`)), { envelope: data });
335  }
336  p.lastError = '';
337  return data;
338}
339type Expected = { generation: number; projection: string };
340function perform($: $, action: Action, moduleId = 'all', expected: Expected | null = null) {
341  return serialized(() => performNow($, action, moduleId, expected));
342}
343// The collector starts one ID or all; a rerun of the failed modules starts each in turn after one check.
344function startFailed($: $, expected: Expected) {
345  return serialized(async () => {
346    await hydrate($);
347    p.busy = true; await publish($);
348    try {
349      await synchronizeIdentity($);
350      await collect($, 'status');
351      if (p.generation !== expected.generation || actionProjection() !== expected.projection) throw new Error('O cadastro ou a execução mudou. Revise os módulos antes de agir.');
352      p.busy = false;
353      const ids = failedIds(), allowed = failedAllowed();
354      p.busy = true;
355      if (!allowed) throw new Error('Início indisponível. Confira os diagnósticos e jobs ativos.');
356      for (const id of ids) await collect($, 'start', id);
357    } catch (error) { p.lastError = errorText(error); }
358    finally { p.busy = false; await publish($); }
359  });
360}
361async function performNow($: $, action: Action, moduleId: string, expected: Expected | null) {
362  await hydrate($);
363  p.busy = true; await publish($);
364  try {
365    await synchronizeIdentity($);
366    if (expected && (p.generation !== expected.generation || actionProjection() !== expected.projection)) throw new Error('A seleção mudou. Atualize o painel antes de agir.');
367    if (expected && ['start', 'cancel', 'logs'].includes(action)) {
368      // Refresh before rendered actions; never act on a renamed module or a replaced run silently.
369      await collect($, 'status');
370      if (p.generation !== expected.generation || actionProjection() !== expected.projection) throw new Error('O cadastro ou a execução mudou. Revise o módulo antes de agir.');
371      if (action === 'start') {
372        p.busy = false;
373        const allowed = moduleId === 'all' ? allAllowed() : startAllowed(moduleId);
374        p.busy = true;
375        if (!allowed) throw new Error('Início indisponível. Confira os diagnósticos e jobs ativos.');
376      }
377    }
378    await collect($, action, moduleId);
379    if (action === 'logs') {
380      const job = p.jobs[moduleId];
381      if (moduleId === 'all') { closeLogs(); p.chooseLogs = true; }
382      else if (job) { p.selectedLogs = { id: moduleId, runId: job.runId }; p.logTail = sanitizeTail(job.logTail); p.logTop = null; p.chooseLogs = false; }
383    }
384  } catch (error) { p.lastError = errorText(error); }
385  finally { p.busy = false; await publish($); }
386}
387const HELP = [
388  '/test-progress — abre ou fecha o painel; não inicia testes.',
389  '/test-progress list — lista módulos ativados, IDs, linguagens e diagnósticos.',
390  '/test-progress start <id|all> — inicia explicitamente os módulos ativados.',
391  '/test-progress status [id|all] — consulta o estado.',
392  '/test-progress logs [id|all] — consulta os logs; escolha um ID no painel.',
393  '/test-progress cancel [id|all] — cancela jobs ativos/recuperáveis desta sessão.',
394  '/test-progress help | paths — ajuda e caminhos instalados.',
395  'Acrescente --text para resposta textual, inclusive no modo headless.',
396  'Cadastro: <diretório da sessão>/.claude/test-progress.json.',
397  'Windows: PowerShell 5.1/7; cancelamento da árvore por Job Object.',
398  'Percentual = testes resolvidos / testes conhecidos. Total parcial pode crescer.',
399  'Cobertura de código e estimativa de tempo não são calculadas.',
400].join('\n');
401const LEGEND = ['● rodando  ✓ ok  ✗ falhou  ■ cancelado  ! erro ou órfão  ○ sem execução',
402  '▶ iniciar  ↻ reinicia os com erro  ■ cancelar  nome abre o log  × fecha o log  ~ total parcial',
403  '⇅ ordena: cadastro → nome → recentes → atenção (falhas primeiro)',
404  'A roda do mouse rola o log aberto; ↓ volta ao fim.',
405  'S/E/T: módulos com sucesso / com erro / total',
406  '✓ passaram  ✗ falharam  ⊘ ignorados',
407  '/test-progress help lista os comandos.'];
408// The app's wheel scrolls its pane, not the log's window (see the log header).
409const APP_SCROLL = '↑ volta uma página do log aberto; ↓ volta ao fim.';
410function textLogs(moduleId: string) {
411  const ids = moduleId === 'all' ? Object.keys(p.jobs).sort() : [moduleId];
412  return ids.flatMap(id => { const job = p.jobs[id]; return job ? [`LOGS · ${id} · ${job.runId}\n${plainTail(job.logTail).join('\n')}`] : []; }).join('\n\n');
413}
414// The app surfaces read a command's text as Markdown, which eats Windows backslashes and pairs of _ or *.
415// A fence keeps it as written; the terminal prints it as is.
416async function verbatim($: $, text: string) {
417  try {
418    const surfaces = await $.session.surfaces();
419    if (!surfaces.length || surfaces.includes('terminal')) return text;
420  } catch { return text; }
421  const fence = '`'.repeat(Math.max(3, ...(text.match(/`+/g) ?? []).map(run => run.length + 1)));
422  // The app writes the command's name before the text, so the fence opens on a line of its own.
423  return `\n${fence}text\n${text}\n${fence}`;
424}
425// A Windows toast; title and text arrive through the environment, never the script.
426const WINDOWS_TOAST = [
427  "$m = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]",
428  "$x = $m::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
429  "$t = $x.GetElementsByTagName('text')",
430  "[void]$t.Item(0).AppendChild($x.CreateTextNode($env:TEST_PROGRESS_NOTIFY_TITLE))",
431  "[void]$t.Item(1).AppendChild($x.CreateTextNode($env:TEST_PROGRESS_NOTIFY_TEXT))",
432  // Under the Claude app's own ID where the desktop app is installed, else PowerShell's.
433  "$p = Get-AppxPackage -Name Claude -ErrorAction SilentlyContinue | Select-Object -First 1",
434  "$id = if ($p) { $p.PackageFamilyName + '!Claude' } else { '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe' }",
435  "$m::CreateToastNotifier($id).Show([Windows.UI.Notifications.ToastNotification]::new($x))",
436].join('; ');
437// Only where the session draws on no terminal: there the terminal's channel already wrote, or chose not to.
438async function systemNotify($: $, title: string, text: string) {
439  try {
440    const surfaces = await $.session.surfaces();
441    if (!surfaces.length || surfaces.includes('terminal')) return false;
442    const cwd = await $.session.cwd();
443    let argv: string[];
444    if (/^[a-z]:[\\/]|^\\\\/i.test(cwd)) {
445      const systemRoot = await $.env.get('SystemRoot');
446      argv = [systemRoot ? `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : 'powershell.exe',
447        '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_TOAST];
448    } else argv = ['notify-send', '--app-name=Test Progress', title, text];
449    const result = await $.process.run(argv, { timeoutMs: 15000,
450      env: { TEST_PROGRESS_NOTIFY_TITLE: title, TEST_PROGRESS_NOTIFY_TEXT: text } });
451    return result.exitCode === 0;
452  } catch { return false; }
453}
454// Typeahead for the command's arguments, read from the last published state: nothing waits on the collector.
455type Suggestion = { text: string; label?: string; description?: string };
456const ACTIONS: [Action, string][] = [['start', 'Inicia um módulo ou todos'], ['status', 'Consulta o estado'],
457  ['logs', 'Consulta o log de um módulo'], ['cancel', 'Cancela a execução ativa'], ['list', 'Lista módulos e IDs'],
458  ['help', 'Comandos do Test Progress'], ['paths', 'Caminhos instalados']];
459const cancellable = (id: string) => { const job = p.jobs[id]; return !!job && (ACTIVE.has(job.status) || !!job.recoveryRequired && !!job.cancellable); };
460function moduleSuggestions(action: Action): Suggestion[] {
461  const names = displayNames();
462  const row = (id: string): Suggestion => {
463    const job = p.jobs[id], state = job && ACTIVE.has(job.status) ? ' · em execução' : job?.recoveryRequired ? ' · órfão' : '';
464    return { text: id, description: `${names[id] ?? id}${state}` };
465  };
466  // Starts reach enabled modules only; a cancel, the runs it can stop; status and logs, all the pane shows.
467  const ids = action === 'start' ? enabled() : action === 'cancel' ? visible().filter(cancellable) : visible();
468  const all = action === 'start' ? enabled().length > 0 : action === 'cancel' ? ids.length > 0 : true;
469  return [...ids.map(row), ...all ? [{ text: 'all', description: action === 'start' ? 'Todos os módulos ativados' : 'Todos os módulos' }] : []];
470}
471function argumentSuggestions(before: string, token: string): Suggestion[] | null {
472  const words = before.trim().split(/\s+/);
473  if (words[0] !== '/test-progress') return null;
474  if (token.startsWith('-')) return words.includes('--text') ? [] : [{ text: '--text', description: 'Resposta em texto' }];
475  const args = words.slice(1).filter(word => word !== '--text');
476  const wanted = token.toLowerCase(), prefix = (text: string) => text.toLowerCase().startsWith(wanted);
477  // A module is found by its ID's start or the start of a word in its label.
478  const named = (id: string) => prefix(id) || (p.modules[id]?.label ?? '').split(/[^\p{L}\p{N}-]+/u).some(prefix);
479  if (!args.length) {
480    // Cancel only while a run of this session can be stopped.
481    const live = visible().some(cancellable);
482    const actions = ACTIONS.filter(([action]) => prefix(action) && (action !== 'cancel' || live)).map(([text, description]) => ({ text, description }));
483    // A module named here completes the whole command: its log while it runs, else a start.
484    const names = displayNames();
485    const shortcuts = visible().filter(named).flatMap((id): Suggestion[] => {
486      const job = p.jobs[id];
487      if (job && ACTIVE.has(job.status)) return [{ text: `logs ${id}`, label: names[id] ?? id, description: `logs ${id} · em execução` }];
488      return p.modules[id]?.enabled ? [{ text: `start ${id}`, label: names[id] ?? id, description: `start ${id}` }] : [];
489    });
490    return [...actions, ...shortcuts];
491  }
492  const action = args[0] as Action;
493  if (args.length > 1 || !['start', 'status', 'logs', 'cancel'].includes(action)) return [];
494  return moduleSuggestions(action).filter(row => prefix(row.text) || row.text !== 'all' && named(row.text));
495}
496// A dim hint after the caret on the command's draft: the modules an action reaches, once the action
497// is typed whole, or the rest of the one row the typed start names. The bare command keeps the
498// engine's own argument hint. Paint only: Enter sends what was typed, Tab takes the row.
499const MODULE_ACTIONS: readonly string[] = ['start', 'status', 'logs', 'cancel'];
500// One line: as many IDs as fit, how many more, then `all`.
501const HINT_WIDTH = 60;
502function moduleList(action: Action): string {
503  const rows = moduleSuggestions(action).map(row => row.text);
504  const all = rows.at(-1) === 'all' ? ['all'] : [], ids = all.length ? rows.slice(0, -1) : rows;
505  const shown: string[] = [];
506  for (const id of ids) {
507    if (shown.length && [...shown, id, '…+99', ...all].join(' | ').length > HINT_WIDTH) break;
508    shown.push(id);
509  }
510  const more = ids.length - shown.length;
511  return [...shown, ...more ? [`…+${more}`] : [], ...all].join(' | ');
512}
513function promptHint(text: string): string {
514  const start = text.search(/\S*$/), token = text.slice(start);
515  const rows = argumentSuggestions(text.slice(0, start), token);
516  if (!rows?.length) return '';
517  const args = text.slice(0, start).trim().split(/\s+/).slice(1).filter(word => word !== '--text');
518  if (!token) return args.length === 1 && MODULE_ACTIONS.includes(args[0]!) ? moduleList(args[0] as Action) : '';
519  // An action typed whole already says what follows it: its modules, past the space still to type.
520  if (!args.length && MODULE_ACTIONS.includes(token)) {
521    const list = moduleList(token as Action);
522    return list ? ` ${list}` : '';
523  }
524  const wanted = token.toLowerCase(), matches = rows.filter(row => row.text.toLowerCase().startsWith(wanted));
525  return matches.length === 1 ? matches[0]!.text.slice(token.length) : '';
526}
527// virtualText came with 2.1.300; set in session.start.
528let canHint = false;
529async function paneShown($: $) {
530  try { return (await $.ui.panes()).some(pane => pane.id === PANE && pane.isShown); } catch { return false; }
531}
532// Runs whose failure already opened the pane once; closing it keeps it closed for those runs.
533const autoOpened = new Set<string>();
534// Once nothing is running, unseen failures open the pane on the first failed module's log, without
535// taking the keyboard. Passing runs never open it. Runs only by the tick, inside its serialized task.
536// The host may hold the pane until the terminal is wide enough; the band still reports meanwhile.
537async function autoOpen($: $) {
538  if (Object.values(p.jobs).some(job => ACTIVE.has(job.status))) return;
539  const failed = visible().filter(id => { const job = p.jobs[id]; return !!job && finishedWithFailure(job) &&
540    !p.seenRuns.includes(job.runId) && !autoOpened.has(job.runId); });
541  if (!failed.length) return;
542  for (const id of failed) autoOpened.add(p.jobs[id]!.runId);
543  // A native notification reaches the person away from the terminal, or where the pane waits for width.
544  // Their own channel and Notification hooks decide; a refusal or a missing channel changes nothing here.
545  const names = displayNames();
546  const notice = failed.map(id => { const count = p.jobs[id]!.failed ?? 0; return `${names[id] ?? id} (${count ? `${count} ✗` : 'erro'})`; });
547  // With no terminal (the desktop app) only Notification hooks run and nothing native is written:
548  // the system's own notifier stands in, and a toast in the app where none answers.
549  const text = `Falharam: ${notice.join(', ')}`;
550  void Promise.resolve().then(() => $.ui.notify(text, { title: 'Test Progress' })).catch(() => null)
551    .then(async sent => { if (!sent?.isSent && !await systemNotify($, 'Test Progress', text)) $.ui.toast(text, { timeoutMs: 10000 }); })
552    .catch(() => {});
553  try {
554    if ((await $.ui.panes()).some(pane => pane.id === PANE)) return;
555    const first = failed[0]!;
556    await collect($, 'logs', first);
557    const job = p.jobs[first];
558    if (job) { p.selectedLogs = { id: first, runId: job.runId }; p.logTail = sanitizeTail(job.logTail); p.logTop = null; p.chooseLogs = false; }
559    await $.ui.open({ id: PANE, title: 'Test Progress' });
560  } catch { /* No pane in this surface: the band and the command remain. */ }
561}
562// The model's own tool: the same collector, queue and state as the pane, without Bash. Its schema is
563// listed from the first prompt (isDeferred: false); the run-tests skill stays as the Bash fallback.
564const TOOL = 'tests', TOOL_NAME = 'mcp__test-progress__tests';
565const TOOL_ACTIONS = ['list', 'start', 'status', 'logs', 'cancel'] as const;
566type ToolAction = typeof TOOL_ACTIONS[number];
567const TOOL_SPEC = {
568  name: TOOL,
569  description: 'Roda e acompanha pelo coletor do Test Progress as suítes cadastradas em .claude/test-progress.json, ' +
570    'no mesmo estado do painel e da faixa desta sessão, sem Bash. Use para a suíte inteira de um módulo, a pedido ' +
571    'ou para conferir uma mudança; não para um teste ou arquivo isolado. list: módulos, IDs, labels e diagnósticos. ' +
572    'start: inicia um ID ou all; um módulo em preparing/running não reinicia, acompanhe-o. status: repita, espaçado ' +
573    'pelo porte da suíte, até jobs.<id>.status sair de preparing/running; relate passed, failed, skipped, total e ' +
574    'exitCode. logs: jobs.<id>.logTail, para citar falhas. cancel: cancela; confirme com status. Responde o JSON do ' +
575    'coletor. Diagnóstico, cadastro ou recoveryRequired: carregue a skill test-progress:configure.',
576  inputSchema: { type: 'object', additionalProperties: false, required: ['action'], properties: {
577    action: { type: 'string', enum: TOOL_ACTIONS },
578    module: { type: 'string', description: 'ID do módulo ou "all" (padrão). list ignora.' },
579  } },
580  isDeferred: false,
581};
582const SUBAGENT_REFUSAL = 'Este agente roda em outro diretório que o painel desta sessão, e a ferramenta só atende o ' +
583  'diretório do painel. Carregue a skill test-progress:run-tests e rode o coletor pelo Bash com o seu próprio --cwd.';
584// Before 2.1.296 a subagent's $ answers the session's folder, so its own folder is unknown: refuse it the same way.
585const SUBAGENT_UNKNOWN = 'Esta versão do Claude Code não informa o diretório de um subagente, e a ferramenta só atende o ' +
586  'diretório do painel. Carregue a skill test-progress:run-tests e rode o coletor pelo Bash com o seu próprio --cwd.';
587// Whether the engine is at least 2.1.<patch>; the desktop app runs its own, which may lag.
588async function engineAtLeast($: $, since: number) {
589  try {
590    const [major = 0, minor = 0, patch = 0] = ((await $.session.version()).base ?? '').split(/[.-]/).map(Number);
591    return major * 1e6 + minor * 1e3 + patch >= since;
592  } catch { return false; }
593}
594const knowsAgentFolder = ($: $) => engineAtLeast($, 2001296);
595// What the model reads: the collector's envelope without the Mod's own bookkeeping (Node path, watched files),
596// and for one module only that module's entry and job, so a status loop does not repeat the whole catalogue.
597function toolAnswer(data: ReturnType<typeof validateEnvelope>, moduleId: string) {
598  const { collector: _collector, sources: _sources, ...rest } = data;
599  if (moduleId === 'all') return JSON.stringify(rest);
600  const only = <T,>(record: Record<string, T>) => moduleId in record ? { [moduleId]: record[moduleId] } : {};
601  return JSON.stringify({ ...rest, modules: only(rest.modules), jobs: only(rest.jobs),
602    stateDiagnostics: { ...only(rest.stateDiagnostics), ...(rest.stateDiagnostics['*'] ? { '*': rest.stateDiagnostics['*'] } : {}) } });
603}
604// Why a start the pane would refuse is refused, in words the model can act on; empty when it may start.
605function startRefusals(moduleId: string) {
606  const config = p.workspace?.moduleConfig?.status;
607  if (config !== 'valid') return [`Cadastro ${configStatus[config ?? ''] ?? 'não consultado'}: confira .claude/test-progress.json com a skill test-progress:configure.`];
608  if (p.workspace?.stateBlocked || p.stateDiagnostics['*']?.length) return ['Estado do coletor bloqueado: veja stateDiagnostics e carregue test-progress:configure.'];
609  const ids = moduleId === 'all' ? enabled() : [moduleId];
610  if (!ids.length) return ['Nenhum módulo ativado neste workspace.'];
611  return ids.flatMap(id => {
612    const module = p.modules[id], job = p.jobs[id];
613    if (!module) return [`${id}: módulo não cadastrado; use action "list".`];
614    if (!module.enabled) return [`${id}: módulo desativado no cadastro.`];
615    if (job && ACTIVE.has(job.status)) return [`${id}: já está ${labels[job.status] ?? job.status} (${job.runId}); acompanhe com status.`];
616    if (job?.recoveryRequired) return [`${id}: run anterior requer recuperação; carregue test-progress:configure.`];
617    if (!module.directoryPresent || diagnostics(id).length) return [`${id}: tem diagnósticos (${diagnostics(id).map(diagnosticText).join('; ') || 'diretório ausente'}).`];
618    return [];
619  });
620}
621// start and cancel run or stop commands from a file the model can edit: the person's permission rules
622// for this tool decide, and an "ask" asks them. Reading (list, status, logs) needs no permission.
623async function toolPermission($: $, tool: string, input: { action: ToolAction; module: string }) {
624  let verdict;
625  try { verdict = await $.tool.check({ tool, input }); }
626  catch (error) { return `Permissão não confirmada: ${errorText(error)}`; }
627  if (verdict.decision === 'allow') return null;
628  if (verdict.decision === 'deny') return `Recusado pelas regras de permissão: ${verdict.reason ?? TOOL_NAME}.`;
629  const target = input.module === 'all' ? 'de todos os módulos' : `do módulo ${input.module}`;
630  const question = input.action === 'start' ? `Iniciar os testes ${target} pelo Test Progress?` : `Cancelar os testes ${target}?`;
631  try {
632    const answer = await $.ui.ask(question, { header: 'Testes', options: ['Permitir', 'Recusar'] });
633    return answer === 'Permitir' ? null : 'A pessoa recusou.';
634  } catch {
635    return `Sem confirmação da pessoa (diálogo fechado ou sessão sem interface). Libere ${TOOL_NAME} nas permissões ou use o painel.`;
636  }
637}
638function serveTool($: $, action: ToolAction, moduleId: string) {
639  return serialized(async () => {
640    await hydrate($);
641    p.busy = true; await publish($);
642    try {
643      if (action === 'start') {
644        // Refresh first, then refuse exactly what the pane's start button would.
645        await collect($, 'status');
646        const refusals = startRefusals(moduleId);
647        if (refusals.length) return { deny: refusals.join('\n') };
648      }
649      return { result: toolAnswer(await collect($, action, moduleId) as ReturnType<typeof validateEnvelope>, moduleId) };
650    } catch (error) {
651      p.lastError = errorText(error);
652      const envelope = (error as { envelope?: ReturnType<typeof validateEnvelope> }).envelope;
653      return envelope ? { result: toolAnswer(envelope, moduleId) } : { deny: p.lastError };
654    } finally { p.busy = false; await publish($); }
655  });
656}
657export const register: Register = on => {
658  on('session.start', async ($, e, next) => {
659    await hydrate($);
660    canHint = await engineAtLeast($, 2001300);
661    timer?.cancel();
662    timer = $.clock.every(1000, () => {
663      // A waiting command already refreshes state; never stack ticks behind it.
664      if (queued) return;
665      void serialized(async () => {
666        try {
667          await synchronizeIdentity($);
668          if (watcher && watcher.identity !== p.identity) stopWatcher();
669          if (await pollDue($)) {
670            // Every query returns the whole catalogue and all jobs; only a live selected run re-reads its log.
671            const selected = p.selectedLogs, job = selected && p.jobs[selected.id];
672            const live = !!selected && !!job && ACTIVE.has(job.status);
673            const streaming = liveJobs() && watch($, live ? selected.id : 'all');
674            if (streaming && watcher && Date.now() - watcher.seenAt > WATCH_STALE_MS) stopWatcher();
675            if (!streaming || !watcher) await collect($, live ? 'logs' : 'status', live ? selected.id : 'all');
676          }
677        } catch (error) { p.lastError = errorText(error); }
678        if (await paneShown($)) acknowledge();
679        else await autoOpen($);
680        await publish($);
681      });
682    });
683    await perform($, 'status');
684    try {
685      // Keep one generic hint; no catalogue updates overwrite another command's registration.
686      const existing = (await $.command.list()).find(command => command.name === 'test-progress');
687      if (existing && (existing.source !== 'plugin' || existing.plugin !== 'test-progress')) {
688        throw new Error('O comando test-progress já existe; origem não pertence a este plugin.');
689      }
690      await $.command.register({ name: 'test-progress', description: 'Painel de execução de testes em segundo plano',
691        argumentHint: '[list|start|status|logs|cancel|help|paths] [id|all] [--text]', immediate: true });
692      p.registrationError = '';
693    } catch (error) { p.registrationError = errorText(error); }
694    // Without the tool the run-tests skill still works through Bash.
695    await $.tool.register(TOOL_SPEC).catch(error => $.ui.log(`Ferramenta ${TOOL_NAME} indisponível: ${errorText(error)}`, { to: 'debug' }));
696    await publish($);
697    return next(e);
698  });
699  on('session.end', async ($, e, next) => {
700    // Poll survives clear/resume/branch; workers and timer aren't cancelled here.
701    stopWatcher();
702    await hydrate($);
703    p = { ...empty(), generation: p.generation + 1, registrationError: p.registrationError, collector: p.collector, sort: p.sort };
704    await publish($);
705    return next(e);
706  });
707  on('command.run', { command: 'test-progress' }, async ($, e, next) => {
708    const answer = await (async () => {
709      await hydrate($);
710      // A name match alone isn't ownership: register() can have failed, or another
711      // command can have replaced our name since startup. Preserve its full result.
712      if (p.registrationError) return next(e);
713      try {
714        const current = (await $.command.list()).find(command => command.name === 'test-progress');
715        if (!current || current.source !== 'plugin' || current.plugin !== 'test-progress') {
716          p.registrationError = 'O comando test-progress está indisponível ou pertence a outra origem.';
717          await publish($);
718          return next(e);
719        }
720      } catch (error) {
721        p.registrationError = `Não foi possível confirmar a origem do comando: ${errorText(error)}`;
722        await publish($);
723        return next(e);
724      }
725      let command;
726      try { command = parseCommand(e.args); } catch (error) { return { text: errorText(error) }; }
727      if (command.action === 'help') return { text: HELP };
728      if (command.action === 'paths') return { text: [`Plugin: ${$.plugin.root}`,
729        `Rails: ${$.plugin.root}/adapters/rails/run.rb`, `Python: ${$.plugin.root}/adapters/python/run.py`,
730        `Karma: ${$.plugin.root}/adapters/karma/reporter.cjs`, `JUnit: ${$.plugin.root}/adapters/junit/pom.xml`,
731        `Ruby / RSpec: ${$.plugin.root}/adapters/ruby/run.rb`,
732        `Playwright: ${$.plugin.root}/adapters/playwright/reporter.cjs`, `Exemplos: ${$.plugin.root}/config.example.json`].join('\n') };
733      // A bare /test-progress toggles: an open pane closes, a closed one refreshes and opens.
734      if (!String(e.args ?? '').trim()) {
735        try {
736          if ((await $.ui.panes()).some(pane => pane.id === PANE)) { await $.ui.close({ id: PANE }); return {}; }
737        } catch { /* No pane record: open as usual. */ }
738      }
739      await perform($, command.action, command.moduleId);
740      if (command.text || command.action === 'list') return { text: textSummary() + (command.action === 'logs' ? `\n${textLogs(command.moduleId)}` : '') };
741      try {
742        const placement = await $.ui.open({ id: PANE, title: 'Test Progress', focus: true, closeOnEscape: true });
743        if (!placement.isPlaced) return { text: `${textSummary()}\nPainel aguardando espaço: ${placement.reason}` };
744        acknowledge(); await publish($);
745      } catch (error) { return { text: `${textSummary()}\nPainel indisponível: ${errorText(error)}` }; }
746      return {};
747    })();
748    // Another command's run (ref) passes untouched; our own text is plain, so it stays verbatim everywhere.
749    return answer.ref === undefined && answer.text ? { ...answer, text: await verbatim($, answer.text) } : answer;
750  });
751  on('prompt.autocomplete', async ($, e, next) => {
752    const below = await next(e);
753    // Other drafts, and a command name this plugin does not own, keep only what lies beneath.
754    if (!e.text.startsWith('/test-progress ')) return below;
755    await hydrate($);
756    if (p.registrationError) return below;
757    const mine = argumentSuggestions(e.text.slice(0, e.start), e.token);
758    return mine?.length ? { suggestions: [...below.suggestions, ...mine] } : below;
759  });
760  on('prompt.edit', async ($, e, next) => {
761    const box = await next(e);
762    if (!canHint || !box.text.startsWith('/test-progress ') || box.cursor !== box.text.length) return box;
763    await hydrate($);
764    if (p.registrationError) return box;
765    const hint = promptHint(box.text);
766    if (!hint) return box;
767    const at = box.text.length;
768    return { ...box, decorations: [...box.decorations ?? [], { start: at, end: at, virtualText: hint, dimColor: true }] };
769  });
770  // A RegExp matcher: the literal name type-checks only once the generated MCP types declare this tool.
771  on('tool.call', { tool: /^mcp__test-progress__tests$/ }, async ($, e) => {
772    const input = e as unknown as { action?: unknown; module?: unknown; agentId?: string };
773    const action = TOOL_ACTIONS.find(name => name === input.action);
774    if (!action) return { deny: `action deve ser ${TOOL_ACTIONS.join(', ')}.` };
775    let moduleId = 'all';
776    try {
777      if (input.module !== undefined && typeof input.module !== 'string') throw new Error('module deve ser um ID ou "all".');
778      if (action !== 'list') moduleId = parseCommand(`${action} ${input.module ?? 'all'}`).moduleId;
779    } catch (error) { return { deny: errorText(error) }; }
780    if (input.agentId) {
781      // A subagent's $ answers its own folder (2.1.296); another folder would replace the pane's identity.
782      if (!await knowsAgentFolder($)) return { deny: SUBAGENT_UNKNOWN };
783      await hydrate($);
784      const [panelCwd] = p.identity.split('\n');
785      if (!panelCwd || await $.session.cwd() !== panelCwd) return { deny: SUBAGENT_REFUSAL };
786    }
787    if (action === 'start' || action === 'cancel') {
788      const refusal = await toolPermission($, e.tool, { action, module: moduleId });
789      if (refusal) return { deny: refusal };
790    }
791    return serveTool($, action, moduleId);
792  });
793  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
794    // Reading the host's value subscribes this drawing; each publish redraws it.
795    await read($, panel);
796    await hydrate($);
797    const elements = $.ui.resolve(e);
798    const { Box, Text, Button } = elements;
799    // The terminal lays out in character cells; the app surfaces draw native buttons and a proportional font.
800    const Svg = e.surface !== 'terminal' && 'Svg' in elements ? elements.Svg : null;
801    const expected = { generation: p.generation, projection: actionProjection() };
802    const guarded = (fn: () => Promise<void> | void) => async () => {
803      await synchronizeIdentity($);
804      if (p.generation !== expected.generation || actionProjection() !== expected.projection) {
805        p.lastError = 'A seleção mudou. Tente de novo.'; await publish($); return;
806      }
807      acknowledge();
808      await fn();
809      await publish($);
810    };
811    const bodyColumns = typeof e.props?.bodyColumns === 'number' ? e.props.bodyColumns : 80;
812    const narrow = bodyColumns < NARROW_COLUMNS;
813    // Button has no disabled prop in the native API. Dim and guard instead of inventing HTML attributes.
814    const button = (key: string, label: string, action: Action, id = 'all', allowed = true) =>
815      <Button key={key} label={label} plain dimColor={p.busy || !allowed}
816        onPress={guarded(async () => { if (allowed) await perform($, action, id, expected); })} />;
817    const local = (key: string, label: string, fn: () => void) => <Button key={key} label={label} plain onPress={guarded(fn)} />;
818    const names = displayNames();
819    const toggleLogs = (id: string) => guarded(async () => {
820      if (p.selectedLogs?.id === id && !p.chooseLogs) { closeLogs(); return; }
821      await perform($, 'logs', id, expected);
822    });
823    // ▶/■ leads the row, in a fixed cell so names stay aligned when a module has neither.
824    const runControl = (id: string) => {
825      const module = p.modules[id], job = p.jobs[id];
826      return <Box key="run" width={Svg ? undefined : 1} flexShrink={0}>{job && (ACTIVE.has(job.status) || job.recoveryRequired && job.cancellable) ? button(`cancel-${id}`, '■', 'cancel', id) :
827        module?.enabled ? button(`start-${id}`, '▶', 'start', id, startAllowed(id)) : null}</Box>;
828    };
829    const progress = (id: string, cells: number) => {
830      const job = p.jobs[id];
831      if (!job) return [<Text key="none" color="inactive">—</Text>];
832      if (job.recoveryRequired) return [<Text key="orphan" color="error">órfão: processo ainda vivo</Text>];
833      const counts = compactCounts(job).map(count => <Text key={count.text} color={count.color}>{`${count.text} `}</Text>);
834      if (!ACTIVE.has(job.status)) {
835        const outcome = outcomeText(job);
836        return [...counts, <Text key="outcome" color={outcome.color}>{outcome.text}</Text>];
837      }
838      const stopping = job.phase === 'cancellation-requested';
839      const bar = progressBar(job, cells);
840      const pct = compactPercent(job);
841      return [
842        Svg ? <Box key="bar" flexShrink={0} paddingRight={1}><Svg source={progressSvg(job, cells * 8, stopping)}
843          alt={pct === '—' ? 'total desconhecido' : `${pct} concluído`} /></Box> :
844        <Box key="bar" flexDirection="row" width={cells + 1}>
845          {bar.done ? <Text key="done" color={stopping ? 'inactive' : 'suggestion'}>{bar.done}</Text> : null}
846          <Text key="rest" color="subtle">{bar.rest}</Text>
847        </Box>,
848        <Box key="pct" width={7}><Text dimColor={stopping}>{pct}</Text></Box>,
849        ...(stopping ? [<Text key="stopping" color="inactive">parando…</Text>] : counts),
850      ];
851    };
852    // The runner's own colors win; a line without any keeps the dim tail and the red error guess.
853    const logLine = (line: string, key: string) => {
854      const spans = ansiSpans(line);
855      const text = spans.map(span => span.text).join('');
856      if (!spans.some(span => span.style)) return /\b(ERROR|FAIL(ED|URE)?)\b/.test(text) ?
857        <Text key={key} wrap="truncate-end" color="error">{`│ ${text}`}</Text> :
858        <Text key={key} wrap="truncate-end" dimColor>{`│ ${text}`}</Text>;
859      return <Text key={key} wrap="truncate-end">
860        <Text dimColor>{'│ '}</Text>
861        {spans.map((span, j) => span.style ? <Text key={`s${j}`} {...span.style}>{span.text}</Text> : <Text key={`s${j}`} dimColor>{span.text}</Text>)}
862      </Text>;
863    };
864    const logBlock = (id: string) => {
865      const selected = p.selectedLogs;
866      if (selected?.id !== id) return [];
867      const job = p.jobs[id];
868      const changed = job?.runId !== selected.runId;
869      const { top, max } = logWindow(), total = p.logTail.length;
870      const lines = p.logTail.slice(top, top + LOG_ROWS);
871      const range = total <= LOG_ROWS ? `${total} ${total === 1 ? 'linha' : 'linhas'}` :
872        top === max ? `últimas ${lines.length} de ${total} linhas` : `linhas ${top + 1}–${top + lines.length} de ${total}`;
873      const header = `log · run ${selected.runId.slice(0, 8)} · ${range}`;
874      return [
875        <Box key={`log-${id}`} flexDirection="column" paddingLeft={4}>
876          <Box key="log-header" flexDirection="row" justifyContent="space-between">
877            <Text key="log-title" color="inactive" wrap="truncate-end">{`│ ${header}`}</Text>
878            <Box key="log-actions" flexDirection="row" flexShrink={0} gap={1}>
879              {/* The app sizes the pane to its tree and scrolls it itself, so no wheel reaches the log's window: page it here. */}
880              {Svg && top > 0 ? local(`up-logs-${id}`, '↑', () => { p.logTop = Math.max(0, top - LOG_ROWS); }) : null}
881              {top < max ? local(`end-logs-${id}`, '↓', () => { p.logTop = null; }) : null}
882              {local(`close-logs-${id}`, '×', closeLogs)}
883            </Box>
884          </Box>
885          {changed && job ? <Box key="changed" flexDirection="row" gap={1}>
886            <Text color="inactive">│ nova execução</Text>
887            {button('select-current-logs', '↻', 'logs', id)}
888          </Box> : null}
889          {lines.length ? lines.map((line, i) => logLine(line, `log-${selected.runId}-${top + i}`)) :
890            <Text key="empty" color="inactive">│ sem saída ainda</Text>}
891        </Box>,
892      ];
893    };
894    // Errors are the line the person most needs whole: they wrap, then point at the next step.
895    const problemBlock = (id: string) => {
896      const job = p.jobs[id];
897      const problems = [...diagnostics(id).map(diagnosticText), ...(job?.error ? [job.error] : [])];
898      if (!problems.length) return [];
899      const hint = job && p.selectedLogs?.id !== id ? '→ clique no nome para abrir o log' + (job.phase === 'no-progress-observed' || /eventos de progresso/.test(job.error ?? '') ?
900        ' · confira o "adapter" do módulo' : '') : '';
901      return [
902        <Box key="problems" flexDirection="column" paddingLeft={4}>
903          {problems.slice(0, 2).map((item, i) => <Text key={`problem-${i}`} color="error" wrap="wrap">{item}</Text>)}
904          {hint ? <Text key="hint" dimColor wrap="wrap">{hint}</Text> : null}
905        </Box>,
906      ];
907    };
908    const row = (id: string) => {
909      const job = p.jobs[id], module = p.modules[id];
910      const { glyph, color } = statusGlyph(job);
911      const time = job ? clock(job.elapsedMs) : '';
912      const live = !!job && ACTIVE.has(job.status);
913      const head = [
914        <Box key="glyph" width={1}><Text color={color} bold>{glyph}</Text></Box>,
915        runControl(id),
916        // With a run, the name opens and closes its log.
917        <Box key="name" flexGrow={1} flexShrink={1} overflow="hidden">{job ?
918          <Button key={`logs-${id}`} label={names[id] ?? id} plain dimColor={!module?.enabled || p.busy && p.selectedLogs?.id !== id} onPress={toggleLogs(id)} /> :
919          <Text wrap="truncate" bold={!!module?.enabled} dimColor={!module?.enabled}>{names[id] ?? id}</Text>}</Box>,
920      ];
921      const tail = <Box key="tail" flexDirection="row" flexShrink={0} gap={1}>
922        {time ? <Text key="time" dimColor>{time}</Text> : null}
923      </Box>;
924      // The name takes the free space, so results and actions stay right-aligned at any width.
925      // Narrow: a finished result fits the name line; only a live bar takes a second one.
926      const middle = <Box key="middle" flexDirection="row" flexShrink={0}>{progress(id, narrow ? 10 : 12)}</Box>;
927      return <Box key={`module-${id}`} flexDirection="column">
928        <Box key="line" flexDirection="row" gap={1}>{head}{narrow && live ? null : middle}{tail}</Box>
929        {narrow && live ? <Box key="progress" flexDirection="row" paddingLeft={4}>{progress(id, 10)}</Box> : null}
930        {problemBlock(id)}
931        {logBlock(id)}
932      </Box>;
933    };
934    const ids = sortModuleIds(visible(), p.modules, p.jobs, p.sort);
935    const configured = ['absent', 'valid'].includes(p.workspace?.moduleConfig?.status ?? 'absent');
936    const counts = summaryCounts(ids, p.jobs);
937    return <Box key="module-list" flexDirection="column">
938      <Box key="toolbar" flexDirection="row" justifyContent="space-between">
939        <Box key="summary" flexDirection="row" gap={2}>
940          <Box key="counts" flexDirection="row">
941            <Text key="passed" color="success">{`${counts.passed}`}</Text>
942            <Text key="sep-1" dimColor>/</Text>
943            <Text key="failed" color="error">{`${counts.failed}`}</Text>
944            <Text key="sep-2" dimColor>/</Text>
945            <Text key="total" dimColor>{`${counts.total}`}</Text>
946          </Box>
947          {enabled().length >= 2 ? button('start-all', '▶ Todos', 'start', 'all', allAllowed()) : null}
948          {/* Button takes no color at rest; the whole label is the target and turns red under the pointer. Hidden while nothing failed. */}
949          {failedIds().length ? <Box key="failed-action"><Button key="start-failed" label="↻ Apenas com erro" plain hover={{ color: 'error' }}
950            dimColor={p.busy || !failedAllowed()} onPress={guarded(async () => { if (failedAllowed()) await startFailed($, expected); })} /></Box> : null}
951          {p.busy ? <Text key="busy" dimColor>…</Text> : null}
952        </Box>
953        <Box key="toolbar-actions" flexDirection="row" gap={1}>
954          {ids.length >= 2 ? local('sort', p.sort === 'order' ? '⇅' : `⇅ ${sortLabels[p.sort]}`, () => { p.sort = nextSort(p.sort); }) : null}
955          {local('help', '?', () => { p.showHelp = !p.showHelp; })}
956        </Box>
957      </Box>
958      {ids.map(row)}
959      {!ids.length && configured && !p.workspace?.error ? <Text key="empty" dimColor>Nenhum módulo em .claude/test-progress.json</Text> : null}
960      {p.chooseLogs ? <Text key="choose-logs" dimColor>Clique no nome de um módulo para ver o log.</Text> : null}
961      {p.selectedLogs && !ids.includes(p.selectedLogs.id) ? logBlock(p.selectedLogs.id) : null}
962      {p.workspace?.error ? <Text key="config-error" color="error" wrap="wrap">{`Configuração: ${p.workspace.error}`}</Text> : null}
963      {(p.workspace?.moduleConfig?.diagnostics ?? []).map((item, i) => <Text key={`config-${i}`} color="error" wrap="wrap">{`Configuração: ${diagnosticText(item)}`}</Text>)}
964      {(p.stateDiagnostics['*'] ?? []).map((item, i) => <Text key={`state-${i}`} color="error" wrap="wrap">{`Estado: ${diagnosticText(item)}`}</Text>)}
965      {p.lastError ? <Text key="last-error" color="error" wrap="wrap">{p.lastError}</Text> : null}
966      {p.registrationError ? <Text key="registration" color="error" wrap="wrap">{`Registro: ${p.registrationError}`}</Text> : null}
967      {p.showHelp ? (Svg ? LEGEND.map(line => line.startsWith('A roda') ? APP_SCROLL : line) : LEGEND).map((line, i) => <Text key={`legend-${i}`} dimColor wrap="wrap">{line}</Text>) : null}
968    </Box>;
969  });
970  // With a log open, the wheel moves the log's own window; at its edges, and for the keys, the pane scrolls.
971  on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
972    await hydrate($);
973    if (!p.selectedLogs || e.origin.kind !== 'person' || !e.pointer) return next(e);
974    const { top, max } = logWindow(), to = Math.min(max, Math.max(0, top + e.by));
975    if (to === top) return next(e);
976    p.logTop = to === max ? null : to;
977    await publish($);
978    return {};
979  });
980  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
981    const existing = await next(e);
982    if (e.props?.hasSurvey) return existing;
983    await read($, panel);
984    await hydrate($);
985    const seen = new Set(p.seenRuns);
986    const live = (id: string) => { const job = p.jobs[id]!; return ACTIVE.has(job.status) || !!job.recoveryRequired; };
987    const failed = (id: string) => { const job = p.jobs[id]!; return ['failed', 'error'].includes(job.status) || (job.failed ?? 0) > 0; };
988    const ids = visible().filter(id => p.jobs[id]);
989    const active = ids.filter(live), unseenFailures = ids.filter(id => !live(id) && failed(id) && !seen.has(p.jobs[id]!.runId));
990    // Nothing running and nothing new to report: the band steps aside.
991    if (!active.length && !unseenFailures.length) return existing;
992    const passed = ids.filter(id => !live(id) && !failed(id) && p.jobs[id]!.status === 'completed');
993    const shown = [...active, ...unseenFailures, ...passed];
994    const { Box, Text } = $.ui.resolve(e);
995    const names = displayNames();
996    const parts = (id: string) => {
997      const job = p.jobs[id]!, { glyph, color } = statusGlyph(job), pct = compactPercent(job);
998      return { glyph, color, name: names[id] ?? id, orphan: !!job.recoveryRequired,
999        progress: job.recoveryRequired || !live(id) ? '' : pct === '—' ? ` ${job.resolved ?? 0}` : ` ${pct}`, dim: pct === '—',
1000        failed: !job.recoveryRequired && (job.failed ?? 0) > 0 ? ` ✗${job.failed}` : '' };
1001    };
1002    const item = (id: string) => {
1003      const { glyph, color, name, orphan, progress, dim, failed } = parts(id);
1004      return <Box key={`summary-${id}`} flexDirection="row">
1005        <Text key="glyph" color={color}>{`${glyph} `}</Text>
1006        <Text key="name">{name}</Text>
1007        {orphan ? <Text key="state" color="error">{' órfão'}</Text> :
1008          progress ? (dim ? <Text key="resolved" dimColor>{progress}</Text> : <Text key="pct">{progress}</Text>) : null}
1009        {failed ? <Text key="failed" color="error">{failed}</Text> : null}
1010      </Box>;
1011    };
1012    // As many items as the line holds, leaving room for the host's own corner control and the "+N" tail.
1013    const SEP = '  ·  ', width = (s: string) => [...s].length;
1014    const itemWidth = (id: string) => { const x = parts(id); return 2 + width(x.name) + (x.orphan ? 6 : width(x.progress)) + width(x.failed); };
1015    const room = (typeof e.props?.bodyColumns === 'number' ? e.props.bodyColumns : 80) - BAND_RESERVE;
1016    let fit = 0, used = 0;
1017    for (const id of shown) {
1018      const end = used + (fit ? SEP.length : 0) + itemWidth(id), rest = shown.length - fit - 1;
1019      if (fit && end + (rest ? width(`${SEP}+${rest}`) : 0) > room) break;
1020      fit++; used = end;
1021    }
1022    const children = shown.slice(0, fit).flatMap((id, i) => [...(i ? [<Text key={`sep-${i}`} dimColor>{SEP}</Text>] : []), item(id)]);
1023    return <Box flexDirection="column">
1024      {existing ?? null}
1025      <Box key="band" flexDirection="row" overflow="hidden">
1026        {children}
1027        {shown.length > fit ? <Text key="more" dimColor>{`${SEP}+${shown.length - fit}`}</Text> : null}
1028      </Box>
1029    </Box>;
1030  });
1031};
1032
runner/module-presentation.mjs 267 lines
1// Pure presentation rules shared by native surfaces and text. No host APIs.
2import { validModuleId } from './module-id.mjs';
3import { SCHEMA_VERSION } from './schema.mjs';
4export const ACTIVE = new Set(['preparing', 'running']);
5export const labels = { preparing: 'Preparando', running: 'Em execução', completed: 'Encerrado',
6  failed: 'Encerrado com falha', cancelled: 'Cancelado', error: 'Erro' };
7const record = value => value && typeof value === 'object' && !Array.isArray(value);
8export function validateEnvelope(data) {
9  const config = data?.workspace?.moduleConfig;
10  if (data?.schemaVersion !== SCHEMA_VERSION || typeof data.ok !== 'boolean' || !record(data.modules) ||
11      !record(data.jobs) || !record(data.stateDiagnostics) || !record(config) ||
12      !['absent', 'valid', 'invalid'].includes(config.status) ||
13      ![SCHEMA_VERSION, null].includes(config.schemaVersion) || !Array.isArray(config.enabledIds)) {
14    throw new Error(`Versão de resposta do coletor incompatível; requer schemaVersion ${SCHEMA_VERSION}.`);
15  }
16  for (const [id, module] of Object.entries(data.modules)) {
17    if (!validModuleId(id) || module?.id !== id || typeof module.label !== 'string' ||
18        !(module.language === null || typeof module.language === 'string') ||
19        !Number.isFinite(module.order) || typeof module.enabled !== 'boolean' ||
20        typeof module.directoryPresent !== 'boolean' || typeof module.origin !== 'string' || !Array.isArray(module.diagnostics)) {
21      throw new Error('Catálogo de módulos inválido na resposta do coletor.');
22    }
23  }
24  for (const [id, job] of Object.entries(data.jobs)) {
25    if (!validModuleId(id) || job?.schemaVersion !== SCHEMA_VERSION || job.moduleId !== id ||
26        typeof job.runId !== 'string' || !job.runId || job.source !== 'config' || !Object.prototype.hasOwnProperty.call(labels, job.status) ||
27        typeof job.phase !== 'string' || job.command !== undefined && !Array.isArray(job.command)) {
28      throw new Error('Snapshot de job incompatível na resposta do coletor.');
29    }
30  }
31  for (const [id, items] of Object.entries(data.stateDiagnostics)) {
32    if (id !== '*' && !validModuleId(id) || !Array.isArray(items)) throw new Error('Diagnósticos de estado inválidos na resposta do coletor.');
33  }
34  if (config.enabledIds.some(id => !validModuleId(id))) throw new Error('IDs de módulos inválidos na resposta do coletor.');
35  return data;
36}
37export function parseCommand(raw) {
38  const tokens = String(raw ?? '').trim().split(/\s+/).filter(Boolean);
39  const text = tokens.includes('--text');
40  const args = tokens.filter(token => token !== '--text');
41  const action = args[0] ?? 'status';
42  if (!['list', 'start', 'status', 'logs', 'cancel', 'help', 'paths'].includes(action) || args.length > 2 ||
43      (['list', 'help', 'paths'].includes(action) && args.length > 1) ||
44      (action === 'start' && args.length !== 2)) throw new Error('Use /test-progress help para consultar os comandos.');
45  const moduleId = args[1] ?? 'all';
46  if (moduleId !== 'all' && !validModuleId(moduleId)) throw new Error('ID de módulo inválido. Use list para ver os IDs.');
47  return { action, moduleId, text };
48}
49export function visibleModuleIds(modules, jobs, diagnostics) {
50  const enabled = Object.keys(modules).filter(id => modules[id].enabled)
51    .sort((a, b) => modules[a].order - modules[b].order || a.localeCompare(b));
52  const retained = new Set(Object.keys(jobs).filter(id => ACTIVE.has(jobs[id].status) || jobs[id].recoveryRequired));
53  for (const id of Object.keys(diagnostics)) if (id !== '*' && validModuleId(id) && diagnostics[id]?.length) retained.add(id);
54  return [...enabled, ...[...retained].filter(id => !enabled.includes(id)).sort()];
55}
56// Panel orderings, cycled by one toolbar button. `order` keeps the catalogue as visibleModuleIds returns it.
57export const SORTS = ['order', 'name', 'recent', 'attention'];
58export const sortLabels = { order: 'cadastro', name: 'nome', recent: 'recentes', attention: 'atenção' };
59export const nextSort = sort => SORTS[(SORTS.indexOf(sort) + 1) % SORTS.length];
60const startedAt = job => { const at = Date.parse(job?.startedAt ?? ''); return Number.isFinite(at) ? at : -Infinity; };
61// What needs a look first: failures and orphans, live runs, cancellations, passes, then modules never run.
62function attention(job) {
63  if (!job) return 4;
64  if (job.recoveryRequired || job.status === 'error') return 0;
65  if (ACTIVE.has(job.status)) return 1;
66  if (job.status === 'failed' || (job.failed ?? 0) > 0) return 0;
67  return job.status === 'cancelled' ? 2 : 3;
68}
69export function sortModuleIds(ids, modules, jobs, sort) {
70  const name = id => modules[id]?.label ?? id;
71  const by = {
72    name: (a, b) => name(a).localeCompare(name(b), 'pt-BR', { sensitivity: 'base', numeric: true }),
73    // Most recent run first; modules without a run keep catalogue order at the end.
74    recent: (a, b) => startedAt(jobs[b]) - startedAt(jobs[a]),
75    attention: (a, b) => attention(jobs[a]) - attention(jobs[b]) || startedAt(jobs[b]) - startedAt(jobs[a]),
76  }[sort];
77  if (!by) return ids;
78  const position = new Map(ids.map((id, i) => [id, i]));
79  return [...ids].sort((a, b) => by(a, b) || position.get(a) - position.get(b));
80}
81export const moduleTitle =(id, module) => `${module?.label ?? id} · ${id}`;
82export function percentage(job) {
83  return typeof job.percent === 'number' && Number.isFinite(job.percent) ? `${job.percent.toFixed(job.percent % 1 ? 1 : 0)}%` : '—';
84}
85export function progressText(job) {
86  if (job.total === 0) return '— [ sem testes ]';
87  if (job.total === null || job.total === undefined || typeof job.percent !== 'number' || !Number.isFinite(job.percent)) return '— [ total desconhecido ]';
88  const filled = Math.max(0, Math.min(16, Math.round(job.percent / 100 * 16)));
89  return `${percentage(job)} [${'■'.repeat(filled)}${'·'.repeat(16 - filled)}]`;
90}
91export function countSummary(job) {
92  const denominator = job.total == null ? 'total desconhecido' : `${job.total} no total${job.totalStable ? '' : ' · total parcial'}`;
93  return `${job.resolved ?? 0} resolvidos / ${denominator}`;
94}
95export const diagnosticText = item => typeof item === 'string' ? item : item?.message ?? item?.code ?? 'Diagnóstico indisponível.';
96export function sanitizeText(value) {
97  return String(value ?? '').replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '')
98    .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/\x1b[@-_]/g, '')
99    .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '').replace(/\t/g, '    ');
100}
101// Log lines keep their SGR color sequences for the panel; every other escape and control goes.
102const SGR = /\x1b\[[\d;:]*m/g;
103export function sanitizeLogText(value) {
104  const text = String(value ?? '').replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '');
105  let result = '', last = 0;
106  for (const match of text.matchAll(SGR)) {
107    result += sanitizeText(text.slice(last, match.index)) + match[0];
108    last = match.index + match[0].length;
109  }
110  return result + sanitizeText(text.slice(last));
111}
112export const sanitizeTail = tail => Array.isArray(tail) ? tail.slice(-200).map(sanitizeLogText) : [];
113export const plainTail = tail => Array.isArray(tail) ? tail.slice(-200).map(sanitizeText) : [];
114// Named colors follow the person's terminal palette; the 256-color cube and truecolor become hex.
115const NAMES = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'];
116const named = index => (index < 8 ? NAMES[index] : `${NAMES[index - 8]}Bright`);
117const hex = (r, g, b) => `#${[r, g, b].map(part => Math.max(0, Math.min(255, part | 0)).toString(16).padStart(2, '0')).join('')}`;
118function palette(index) {
119  if (!(index >= 0 && index <= 255)) return undefined;
120  if (index < 16) return named(index);
121  if (index >= 232) { const level = 8 + (index - 232) * 10; return hex(level, level, level); }
122  const cube = index - 16, level = part => (part ? 55 + part * 40 : 0);
123  return hex(level(Math.floor(cube / 36)), level(Math.floor(cube / 6) % 6), level(cube % 6));
124}
125// Reads the extended color that starts at params[i] (38/48), returning it and how many params it used.
126function extended(params, i) {
127  if (params[i].length > 1) {
128    const parts = params[i];
129    if (parts[1] === 5) return [palette(parts[2]), 1];
130    if (parts[1] === 2) { const rgb = parts.slice(-3); return [rgb.length === 3 ? hex(...rgb) : undefined, 1]; }
131    return [undefined, 1];
132  }
133  const mode = params[i + 1]?.[0];
134  if (mode === 5) return [palette(params[i + 2]?.[0]), 3];
135  if (mode === 2) return [hex(params[i + 2]?.[0], params[i + 3]?.[0], params[i + 4]?.[0]), 5];
136  return [undefined, 1];
137}
138function applySgr(style, body) {
139  const params = (body === '' ? '0' : body).split(';').map(param => param.split(':').map(part => (part === '' ? 0 : Number(part))));
140  for (let i = 0; i < params.length;) {
141    const code = params[i][0];
142    if (code === 0) { for (const name of Object.keys(style)) delete style[name]; i++; continue; }
143    if (code === 38 || code === 48) {
144      const [color, used] = extended(params, i);
145      if (color) style[code === 38 ? 'color' : 'backgroundColor'] = color;
146      i += used; continue;
147    }
148    if (code === 1) style.bold = true;
149    else if (code === 2) style.dimColor = true;
150    else if (code === 3) style.italic = true;
151    else if (code === 4) style.underline = true;
152    else if (code === 7) style.inverse = true;
153    else if (code === 9) style.strikethrough = true;
154    else if (code === 22) { delete style.bold; delete style.dimColor; }
155    else if (code === 23) delete style.italic;
156    else if (code === 24) delete style.underline;
157    else if (code === 27) delete style.inverse;
158    else if (code === 29) delete style.strikethrough;
159    else if (code >= 30 && code <= 37) style.color = named(code - 30);
160    else if (code === 39) delete style.color;
161    else if (code >= 40 && code <= 47) style.backgroundColor = named(code - 40);
162    else if (code === 49) delete style.backgroundColor;
163    else if (code >= 90 && code <= 97) style.color = named(code - 90 + 8);
164    else if (code >= 100 && code <= 107) style.backgroundColor = named(code - 100 + 8);
165    i++;
166  }
167}
168// Splits a sanitized log line into runs of text and the SGR style each one carries (null when plain).
169export function ansiSpans(line) {
170  const text = String(line ?? '');
171  const spans = [], style = {};
172  let last = 0;
173  const push = value => {
174    if (!value) return;
175    const current = Object.keys(style).length ? { ...style } : null;
176    const previous = spans[spans.length - 1];
177    if (previous && JSON.stringify(previous.style) === JSON.stringify(current)) previous.text += value;
178    else spans.push({ text: value, style: current });
179  };
180  for (const match of text.matchAll(SGR)) {
181    push(text.slice(last, match.index));
182    applySgr(style, match[0].slice(2, -1));
183    last = match.index + match[0].length;
184  }
185  push(text.slice(last));
186  return spans;
187}
188// Compact panel and band vocabulary: one-column glyphs so terminal columns stay aligned.
189export function statusGlyph(job) {
190  if (!job) return { glyph: '○', color: 'inactive' };
191  if (job.recoveryRequired || job.status === 'error') return { glyph: '!', color: 'error' };
192  if (ACTIVE.has(job.status)) return job.phase === 'cancellation-requested' ?
193    { glyph: '◌', color: 'inactive' } : { glyph: '●', color: 'warning' };
194  if (job.status === 'cancelled') return { glyph: '■', color: 'inactive' };
195  if (job.status === 'failed' || (job.failed ?? 0) > 0) return { glyph: '✗', color: 'error' };
196  return { glyph: '✓', color: 'success' };
197}
198const knownPercent = job => job.total != null && job.total > 0 && typeof job.percent === 'number' && Number.isFinite(job.percent);
199// A thin bar while a run is live: done cells in the accent, the rest subtle. Unknown totals draw dashes.
200export function progressBar(job, cells = 12) {
201  if (!knownPercent(job)) return { done: '', rest: '╌'.repeat(cells) };
202  const filled = Math.max(0, Math.min(cells, Math.round(job.percent / 100 * cells)));
203  return { done: '━'.repeat(filled), rest: '━'.repeat(cells - filled) };
204}
205// The same bar as an SVG for the app surfaces, whose proportional font widens the glyphs past their cells.
206// An image takes no theme color, so the track is a gray that reads on light and dark backgrounds.
207export function progressSvg(job, width = 96, stopping = false) {
208  const track = '<rect x="0" y="2" width="' + width + '" height="4" rx="2" fill="#8888" />';
209  if (!knownPercent(job)) return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8">` +
210    `<line x1="0" y1="4" x2="${width}" y2="4" stroke="#8888" stroke-width="2" stroke-dasharray="4 3" /></svg>`;
211  const done = Math.round(Math.max(0, Math.min(100, job.percent)) / 100 * width);
212  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8">${track}` +
213    (done ? `<rect x="0" y="2" width="${done}" height="4" rx="2" fill="${stopping ? '#888' : '#4f8ff7'}" />` : '') + '</svg>';
214}
215// A finished run reads as its result, not as a full bar.
216export function outcomeText(job) {
217  if (job.status === 'error') return { text: 'erro', color: 'error' };
218  if (job.status === 'cancelled') return { text: 'cancelado', color: 'inactive' };
219  if (job.total === 0) return { text: '-', color: 'inactive' };
220  // Under `exit` without events the exit code is the whole result.
221  if (job.total == null && job.adapter === 'exit' && Number.isInteger(job.exitCode)) return { text: `exit ${job.exitCode}`, color: 'inactive' };
222  if (job.total == null) return { text: 'total desconhecido', color: 'inactive' };
223  return { text: `· ${job.total}`, color: 'inactive' };
224}
225// A finished run that failed: a failed or errored status, or any failed test.
226export function finishedWithFailure(job) {
227  return !!job && !ACTIVE.has(job.status) && !job.recoveryRequired &&
228    (['failed', 'error'].includes(job.status) || (job.failed ?? 0) > 0);
229}
230// Toolbar summary S/E/T: modules that passed, modules that failed, all modules.
231export function summaryCounts(ids, jobs) {
232  const failed = ids.filter(id => finishedWithFailure(jobs[id])).length;
233  const passed = ids.filter(id => jobs[id]?.status === 'completed' && !finishedWithFailure(jobs[id])).length;
234  return { passed, failed, total: ids.length };
235}
236// Protocol lines are the collector's input, not the person's log; runs of blank lines collapse to one.
237// A line holding only color sequences is as blank as an empty one.
238const blank = line => !line.replace(SGR, '').trim();
239export function readableTail(lines, prefix) {
240  const kept = [];
241  for (const line of lines) {
242    if (line.includes(prefix)) continue;
243    if (blank(line) && (!kept.length || blank(kept[kept.length - 1]))) continue;
244    kept.push(line);
245  }
246  while (kept.length && blank(kept[kept.length - 1])) kept.pop();
247  return kept;
248}
249export function compactPercent(job) {
250  if (job.total === 0) return 'sem testes';
251  if (!knownPercent(job)) return '—';
252  // A finished run's total is final, whatever the stream last claimed.
253  return `${ACTIVE.has(job.status) && !job.totalStable ? '~' : ''}${percentage(job)}`;
254}
255// ⊘ renders flush against the next digit in common terminal fonts, so it keeps a space.
256export function compactCounts(job) {
257  return [['passed', '✓', 'success'], ['failed', '✗', 'error'], ['skipped', '⊘ ', 'inactive']]
258    .filter(([key]) => (job?.[key] ?? 0) > 0).map(([key, glyph, color]) => ({ text: `${glyph}${job[key]}`, color }));
259}
260export function clock(ms) {
261  if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return '';
262  const total = Math.floor(ms / 1000), h = Math.floor(total / 3600), m = Math.floor(total % 3600 / 60), s = total % 60;
263  const pad = value => String(value).padStart(2, '0');
264  return h ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
265}
266export const configStatus = { valid: 'válido', absent: 'ausente', invalid: 'inválido' };
267
runner/module-id.mjs 14 lines
1const reserved = new Set(['all', 'constructor', 'prototype', 'con', 'prn', 'aux', 'nul']);
2
3export function validModuleId(id) {
4  return typeof id === 'string' && /^[a-z][a-z0-9-]{0,47}$/.test(id) &&
5    !reserved.has(id) && !/^(?:com|lpt)[1-9]$/.test(id);
6}
7
8export function requireModuleId(id) {
9  if (validModuleId(id)) return id;
10  const error = new Error('ID de módulo inválido ou reservado.');
11  error.code = 'INVALID_MODULE_ID';
12  throw error;
13}
14
runner/schema.mjs 3 lines
1// Version of every persisted record (configuration, state, batches) and of the collector response.
2export const SCHEMA_VERSION = 1;
3
types/index.d.ts 94 lines
1// Test Progress state contract: what the pane and the band draw, held by the host so a hot reload keeps it.
2
3/** One module of the workspace catalogue, as the collector reports it. */
4export type TestProgressModule = {
5  id: string
6  label: string
7  language: string | null
8  order: number
9  enabled: boolean
10  directoryPresent: boolean
11  origin: string
12  diagnostics: TestProgressDiagnostic[]
13}
14
15/** A diagnostic is either plain text or a coded message. */
16export type TestProgressDiagnostic = string | { code?: string; message?: string; blocking?: boolean }
17
18/** One run's snapshot. Counts are observed, never estimated; `total: null` is unknown, not zero. */
19export type TestProgressJob = {
20  schemaVersion: number
21  moduleId: string
22  runId: string
23  source: 'config'
24  status: 'preparing' | 'running' | 'completed' | 'failed' | 'cancelled' | 'error'
25  phase: string
26  adapter?: string
27  total?: number | null
28  totalStable?: boolean
29  resolved?: number
30  passed?: number
31  failed?: number
32  skipped?: number
33  percent?: number | null
34  exitCode?: number | null
35  elapsedMs?: number
36  startedAt?: string | null
37  endedAt?: string | null
38  error?: string
39  recoveryRequired?: boolean
40  cancellable?: boolean
41  logPath?: string
42  logTail?: string[]
43  heartbeatAt?: string | null
44  lastOutputAt?: string | null
45  lastProgressAt?: string | null
46  collectorRuntime?: { version: string; source: string }
47  nodeRuntime?: { version: string; source: string; nvmrc?: string | null }
48}
49
50export type TestProgressWorkspace = {
51  moduleConfig?: {
52    status: 'absent' | 'valid' | 'invalid'
53    schemaVersion: number | null
54    enabledIds: string[]
55    diagnostics?: TestProgressDiagnostic[]
56  }
57  stateBlocked?: boolean
58  error?: string
59}
60
61/** The Node the collector bootstrapped, reused for later queries of the same identity. */
62export type TestProgressCollector = { identity: string; path: string; source: string }
63
64/** Everything the pane and band draw, plus the session identity it belongs to. */
65export type TestProgressPanel = {
66  identity: string
67  generation: number
68  sessionOwner: string
69  modules: Record<string, TestProgressModule>
70  jobs: Record<string, TestProgressJob>
71  stateDiagnostics: Record<string, TestProgressDiagnostic[]>
72  workspace: TestProgressWorkspace | null
73  busy: boolean
74  lastError: string
75  registrationError: string
76  selectedLogs: { id: string; runId: string } | null
77  logTail: string[]
78  /** First log line shown; null follows the end as the run writes. */
79  logTop: number | null
80  chooseLogs: boolean
81  showHelp: boolean
82  /** How the pane orders modules; kept across identities so a new session reads the same way. */
83  sort: 'order' | 'name' | 'recent' | 'attention'
84  /** Runs the person has seen in the pane; the band keeps only unseen failures. */
85  seenRuns: string[]
86  collector: TestProgressCollector | null
87}
88
89declare module 'claude-code' {
90  interface PluginState {
91    'test-progress': { panel: TestProgressPanel }
92  }
93}
94