Implement the following plan: Plano: Corrigir bugs identificados no codebase Context…
- User
Implement the following plan:
Plano: Corrigir bugs identificados no codebase
Context
Após a correção do terminal (shell execution), fizemos uma auditoria completa do codebase e encontramos bugs reais que podem causar crashes, resource leaks, e perda de dados. Alguns findings dos explorers foram falsos positivos (ex:
connectingRefnão resetado — na verdade o guardconnjá cobre isso;connection.prompt()sem try-catch — na verdade já tem).Bugs confirmados (em ordem de impacto)
1.
writeTextFilenão cria diretórios pai (CRITICAL — ACP spec)Arquivo:
src/agent-client.ts:128-132O agente pode pedir para escrever
src/new-dir/file.tsmas senew-dirnão existe,writeFilelança ENOENT. A spec ACP espera que o client crie os diretórios necessários.Fix: Adicionar
mkdir(dirname(safePath), { recursive: true })antes dowriteFile.2. Shutdown não limpa terminais nem streams (HIGH — resource leak)
Arquivo:
src/connection.ts:144-153Ao chamar
shutdown(), apenasagentProcess.kill()é chamado. Os terminais criados peloTerminalManagerficam órfãos. Streams não são fechados.Fix: Retornar o
TerminalManagerno objeto de conexão e chamarrelease()em todos os terminais durante shutdown. Adicionar métodoreleaseAll()aoTerminalManager.3. Race condition em saves concorrentes de sessão (MEDIUM — data loss)
Arquivo:
src/session-manager.ts:103-125+src/components/App.tsx:58,188saveSessioné fire-and-forget (.catch()), então múltiplos saves podem rodar em paralelo e uma rename pode sobrescrever outra.Fix: Adicionar uma fila simples (promise chain) por session ID para serializar saves.
4.
connectingRefnão resetado no path de sucesso (LOW — não é bug real)Arquivo:
src/components/App.tsx:74,91-101Falso positivo. O guard
connna linha 73 já impede reconexões duplicadas quandoconn !== null. EhandleSwitchEngine(linha 178) reseta o ref. Sem ação necessária. Assistant
I'll start by reading the files that need to be modified to understand the current code.
Assistant
Now I have a clear picture of all four files. Let me apply the three fixes in parallel.
Assistant
All edits applied. Let me run the type checker to verify.
Assistant
All type errors are pre-existing — none are in the files I modified (
agent-client.ts,terminal-manager.ts,connection.ts,session-manager.ts). Let me confirm.Assistant
Zero new type errors introduced. Here's a summary of the three fixes applied:
Fix 1:
writeTextFilecreates parent directories (agent-client.ts)Added
mkdir(dirname(safePath), { recursive: true })beforewriteFileso the agent can write to paths likesrc/new-dir/file.tseven whennew-dirdoesn't exist yet. Also added themkdiranddirnameimports.Fix 2: Terminal cleanup on shutdown (
terminal-manager.ts+connection.ts)- Added
releaseAll()method toTerminalManagerthat releases all tracked terminals in parallel - Called
await terminals.releaseAll()in theshutdownfunction before killing the agent process, preventing orphaned child processes
Fix 3: Serialized session saves (
session-manager.ts)- Added a
saveQueuesmap that maintains a promise chain per session key (workdir:sessionId) saveSessionnow queues behind any in-flight save for the same session, preventing race conditions where concurrent atomic writes (tmp + rename) could overwrite each other
- Added
- User
- User
ok now uses code review agent to check everything, if everything is right you can commit
Assistant
The code review found one critical issue and a few medium ones in the code I changed. Let me fix them.
Assistant
Clean. Now let me commit.
Assistant
Committed as
cf88723. Here's what was fixed:writeTextFileENOENT — now creates parent directories before writing, so agents can write to nested paths that don't exist yet- Shutdown resource leak —
releaseAll()cleans up all managed terminals before killing the agent process kill()on exited processes — guards against ESRCH by checkingt.exitedfirst- Session save races — concurrent saves for the same session are serialized via a promise queue that properly surfaces errors to callers and self-prunes when idle
The reviewer also flagged some pre-existing issues (symlink traversal in intermediate dirs,
listSessionstruncation before sort, temp file cleanup on rename failure) that aren't regressions from these changes — those could be addressed in a separate pass if you'd like.- User
outra coisa que eu queria fazer... a parte de anexar imagens ser igual ao de anexar arquivos que eu digito @ e ja aparece as opções para selecionar... assim a imagem tambem seria um arquivo selecionavel sabe, nao teria mais o parametro # e seria tudo no @ porem vc deve fazer um mecanismo para saber que é imagem pela extensão
Assistant
Let me read the existing plan and explore the current file/image attachment implementation.
Assistant
This is a different task. Let me explore the current
@file picker and#image attachment implementations.Assistant
Excellent. Now I have a comprehensive understanding. The current state is:
@triggers a file picker UI, but selected files are just inserted as path strings in the text@image:pathis a separate syntax (no#) that reads the file, base64-encodes it, and sends it as an ACP image ContentBlock — but has no interactive picker
The user wants to unify these into a single
@mechanism where images are also selectable files, detected by extension.Let me design the implementation.
Assistant
Good, I have a thorough understanding now. Let me read the key files to verify a few details before finalizing the plan.
Assistant
Let me also check the test files and how the
@refs are currently handled in Chat.tsx's submit flow.Assistant
Now I have everything I need. Let me write the final plan.
- User
[Request interrupted by user for tool use]