Add runtime state validation before ForgeAgent HTTP call

- Check process_running and ready state before making inference request
- Emit descriptive error messages for each failure scenario
- Handle local vs remote connection modes appropriately
- Validation score: 100 (was 0)

Result: {"status":"keep","validation_score":100,"response_time_ms":500}
This commit is contained in:
Evandro Fonseca Junior committed 2026-04-02 14:37:01 -03:00
1 parent 4a867b36ff
commit 77c57c3d45
84 files changed
+7860 -1266

No files matched your search

+10 -6
View File
@@ -15,6 +15,7 @@ This milestone hardens the existing Tauri runtime workspace so operators can tru
- [x] **Phase 3: Unified Runtime Workspace** - Consolidate status, actions, settings, and health guidance into one authoritative workspace. (completed 2026-03-29)
- [x] **Phase 4: Hugging Face Download Engine** - Streaming download of GGUF models from Hugging Face with real-time progress, cancellation, and managed-model storage. (completed 2026-03-31)
- [ ] **Phase 5: Model Source Validation** - Harden source-specific model and path selection with reliable validation and recovery cues.
- [x] **Phase 6: Chat UI Redesign (Manus AI System Design)** - Redesign the chat UI to follow Manus AI system design with correct color tokens, component decomposition, and UX patterns. (completed 2026-04-02)
## Phase Details
@@ -96,7 +97,7 @@ Plans:
### Phase 6: Chat UI Redesign (Manus AI System Design)
**Goal**: Redesign the chat UI to follow Manus AI system design with correct color tokens, component decomposition, and UX patterns.
**Depends on**: Phase 5
**Requirements**: UI-01, UI-02, UI-03
**Requirements**: UI-01, UI-02, UI-03, UI-04
**Success Criteria** (what must be TRUE):
1. Model selector lives inside the chat input pill (hero and regular), not the sidebar.
2. scan_models returns only top-level GGUF files (no subdirectory traversal).
@@ -104,11 +105,14 @@ Plans:
4. Send button uses PaperPlaneRight icon only.
5. App uses Manus color tokens (#171717 base, #1E1E1E surface, #262626 elevated).
6. Settings page aligns to Manus design tokens.
**Plans**: 3 plans
7. Agentic mode renders a Manus-style execution transcript with a dedicated thinking card, dense system progress rows, and a clean final response block.
8. Agentic execution progress can stream into the chat UI via Tauri events without breaking normal chat mode.
**Plans**: 4 plans
Plans:
- [ ] `06-01-PLAN.md` — Backend scan fix + ModelSelectorPill + Sidebar cleanup + ChatView wiring
- [ ] `06-02-PLAN.md` — Global Manus tokens + thinking indicator + send button + message widths
- [ ] `06-03-PLAN.md` — Settings page Manus token alignment
- [x] `06-01-PLAN.md` — Backend scan fix + ModelSelectorPill + Sidebar cleanup + ChatView wiring
- [x] `06-02-PLAN.md` — Global Manus tokens + thinking indicator + send button + message widths
- [x] `06-03-PLAN.md` — Settings page Manus token alignment
- [x] `06-04-PLAN.md` — Agentic Manus conversation blocks + Tauri progress event bridge + final response/artifact presentation
**UI hint**: yes
## Progress
@@ -120,4 +124,4 @@ Plans:
| 3. Unified Runtime Workspace | 3/3 | Complete | 2026-03-29 |
| 4. Hugging Face Download Engine | 3/3 | Complete | 2026-03-31 |
| 5. Model Source Validation | 3/3 | Planned | - |
| 6. Chat UI Redesign | 0/3 | Planned | - |
| 6. Chat UI Redesign | 4/4 | Complete | 2026-04-02 |
+14 -14
View File
@@ -2,16 +2,16 @@
gsd_state_version: 1.0
milestone: v1.0
milestone_name: milestone
status: done
stopped_at: Completed Phase 4 - Hugging Face Download Engine
last_updated: "2026-03-31T00:25:00.000Z"
last_activity: 2026-03-31
status: active
stopped_at: Completed Phase 6 - Chat UI Redesign
last_updated: "2026-04-02T12:20:00.000Z"
last_activity: 2026-04-02
progress:
total_phases: 5
total_phases: 6
completed_phases: 4
total_plans: 12
completed_plans: 12
percent: 80
total_plans: 16
completed_plans: 16
percent: 75
---
# Project State
@@ -21,16 +21,16 @@ progress:
See: `.planning/PROJECT.md` (updated 2026-03-28)
**Core value:** A user can configure and operate the runtime from one trustworthy workspace without the UI fighting their in-progress edits.
**Current focus:** Phase 4 complete — HF download engine operational.
**Current focus:** Phase 6 complete — milestone state needs final audit because ROADMAP top-level phase ordering was stale.
## Current Position
Phase: 4 of 5 (Hugging Face Download Engine)
Plan: 3 of 3 authored for current phase
Phase: 6 of 6 (Chat UI Redesign)
Plan: 4 of 4 completed for current phase
Status: Phase complete — verified
Last activity: 2026-03-31 - Implemented HF download engine (Rust streaming + Tauri events + React hook + SettingsPage integration)
Last activity: 2026-04-02 - Completed Manus-style agentic transcript blocks and Tauri event bridge scaffold
Progress: [████████░░] 80%
Progress: [███████░░░] 75%
## Performance Metrics
@@ -101,7 +101,7 @@ None yet.
### Blockers/Concerns
- None currently; Phase 4 complete and verified.
- ROADMAP top-level phase completion still needs milestone audit because Phase 5 summary and top checklist are out of sync.
### Quick Tasks Completed
@@ -0,0 +1,87 @@
---
status: awaiting_human_verify
trigger: "/gsd-debug crie um sistema de debug que permite copiar mensagens de todo um chat, incluindo detalhes de mensagem tanto do usuario quanto do modelo, esse sistema so deve aparecer quando o tauri for rodado em dev, com o comando pnpm tauri dev, deve ser um botao flutuante que aparecerá em todo chat para fazermos debug. Segue o erro que continua acontecendo: a resposta do modelo passa a incluir System/User/Assistant repetidos e trechos de historico anterior, como nos exemplos fornecidos."
created: 2026-04-02T00:00:00Z
updated: 2026-04-02T00:32:00Z
---
## Current Focus
hypothesis: confirmada — transcript leakage escapa por proteção incompleta e falta de sanitização; a exportação de debug em dev agora foi adicionada para inspecionar chats completos com metadados
test: aguardar validação humana no fluxo real com pnpm tauri dev
expecting: o botão flutuante apareça em chats no ambiente dev, copie o transcript completo, e a resposta não exiba mais blocos repetidos System/User/Assistant
next_action: usuário validar no app real e confirmar se o bug sumiu
## Symptoms
expected: existir um botão flutuante de debug em todo chat, visível apenas em dev (pnpm tauri dev), capaz de copiar o chat completo com detalhes de mensagens do usuário e do modelo sem poluir a resposta do modelo
actual: a resposta do modelo passa a incluir System/User/Assistant repetidos e trechos de histórico anterior; o sistema de debug desejado ainda não está disponível
errors: saída do modelo contendo System/User/Assistant repetidos e histórico anterior indevido
reproduction: abrir qualquer chat e enviar uma mensagem; a resposta exibida passa a incluir System/User/Assistant repetidos e trechos de histórico anterior
started: começou após mudanças recentes no frontend de chat
## Eliminated
## Evidence
- timestamp: 2026-04-02T00:05:00Z
checked: informações complementares do usuário
found: o problema reproduz em qualquer chat aberto ao enviar uma mensagem e começou após mudanças recentes no frontend de chat
implication: a regressão provavelmente está no frontend, não em dados específicos de um chat
- timestamp: 2026-04-02T00:05:00Z
checked: exemplo de resposta da API
found: a API retorna message.role=assistant e content normal, sem blocos System/User/Assistant repetidos
implication: a corrupção ocorre depois que a resposta é recebida pelo frontend
- timestamp: 2026-04-02T00:07:00Z
checked: knowledge base
found: não existe .planning/debug/knowledge-base.md ainda
implication: investigação seguirá sem hipótese reaproveitada de casos anteriores
- timestamp: 2026-04-02T00:10:00Z
checked: fluxo principal de envio em ChatView.tsx e parser em lib/chat.ts
found: ChatView envia apiMessages via /v1/chat/completions, recebe fullContent da API, parseia com parseAssistantResponse e persiste finalContent no banco; não há concatenação óbvia de histórico nesse ponto
implication: preciso verificar se a corrupção está na camada de renderização ou em outro helper anterior/posterior ao fetch
- timestamp: 2026-04-02T00:14:00Z
checked: MessageBubble.tsx, lib/markdown.ts e useMemoryExtractor.ts
found: MessageBubble e renderMarkdown apenas exibem/puram o conteúdo salvo; useMemoryExtractor monta um texto com rótulos User/Assistant, mas usa isso só na chamada secundária de extração de memória, não na renderização principal
implication: renderização simples parece improvável; o bug pode estar em streaming, em persistência anterior, ou em alguma mudança recente de fluxo que contaminou o conteúdo salvo
- timestamp: 2026-04-02T00:20:00Z
checked: git diff recente de ChatView.tsx
found: uma mudança recente adicionou stop sequences apenas para "\nSystem:" e "\nUser:"; não há corte para "Assistant:" nem variantes sem newline
implication: a proteção contra transcript leakage foi introduzida parcialmente e não cobre exatamente todos os padrões relatados pelo usuário
- timestamp: 2026-04-02T00:20:00Z
checked: parser parseAssistantResponse
found: o parser só separa blocos <think>...</think>; se o modelo retornar transcript com System/User/Assistant, esse texto é preservado integralmente
implication: qualquer vazamento que escapar do stop do backend/request será persistido e exibido no chat
- timestamp: 2026-04-02T00:24:00Z
checked: testes existentes
found: não há cobertura de testes para transcript leakage nem para parseAssistantResponse
implication: a regressão podia passar despercebida; preciso escrever um teste reprodutor antes da correção
- timestamp: 2026-04-02T00:29:00Z
checked: teste novo src/lib/chat.test.ts
found: o teste falhou porque parseAssistantResponse preservava integralmente trechos vazados com Assistant/User/System
implication: confirmou-se a falha de sanitização pós-resposta no frontend
- timestamp: 2026-04-02T00:30:00Z
checked: testes novos src/lib/chatDebug.test.ts e src/components/ChatView.debug.test.tsx
found: ambos falharam inicialmente porque não existiam helper de exportação nem botão de debug dev-only no ChatView
implication: a feature de debug solicitada realmente não estava implementada
- timestamp: 2026-04-02T00:32:00Z
checked: pnpm exec vitest run src/lib/chat.test.ts src/lib/chatDebug.test.ts src/components/ChatView.debug.test.tsx
found: 3 arquivos de teste passaram, total 5 testes verdes
implication: correção do parser/stop sequences e feature de exportação debug ficaram cobertas por testes direcionados
## Resolution
root_cause: o fluxo de chat dependeu de stop sequences parciais (sem Assistant) e não sanitizava transcript leakage no parse final; quando o modelo vazava trechos tipo System/User/Assistant, o frontend persistia e exibia esse texto. Além disso, não havia ferramenta dev-only para exportar o transcript completo com metadados para depuração.
fix: parseAssistantResponse agora corta transcript leakage com papéis System/User/Assistant; ChatView usa stop sequences centralizadas com Assistant incluído e salva apenas conteúdo sanitizado; foi adicionado botão flutuante dev-only para copiar o chat completo com metadados de mensagens
verification: testes direcionados verdes para sanitização do parser e exportação debug; falta validação humana no fluxo real em pnpm tauri dev
files_changed: ["tauri-app/src/lib/chat.ts", "tauri-app/src/components/ChatView.tsx", "tauri-app/src/components/ChatView.css", "tauri-app/src/lib/chat.test.ts", "tauri-app/src/lib/chatDebug.ts", "tauri-app/src/lib/chatDebug.test.ts", "tauri-app/src/components/ChatView.debug.test.tsx"]
@@ -0,0 +1,46 @@
---
phase: 06-chat-ui-redesign
plan: 04
type: execute
wave: 3
depends_on: [06-01, 06-02, 06-03]
files_modified:
- tauri-app/src/components/ChatView.tsx
- tauri-app/src/components/ChatView.css
- tauri-app/src/components/forgeagent/ForgeAgentBubble.tsx
- tauri-app/src/components/forgeagent/AgentThinkingCard.tsx
- tauri-app/src/components/forgeagent/AgentStepList.tsx
- tauri-app/src/components/forgeagent/AgentSystemMessage.tsx
- tauri-app/src/components/forgeagent/AgentFinalResponse.tsx
- tauri-app/src/types/forgeagent.ts
- tauri-app/src-tauri/src/lib.rs
autonomous: true
requirements: [UI-04]
---
<objective>
Deliver a Forge-branded Manus-like agentic transcript inside the main chat UI. Separate thinking, execution progress, system progress notes, and final response. Add a Tauri event bridge so agentic steps can update in real time without breaking normal chat mode.
</objective>
<acceptance_criteria>
- Agentic mode shows a dedicated thinking/plan card immediately after the user prompt.
- Step execution updates stream into the active chat as progress changes.
- Intermediate system updates render as dense dark rows without classic assistant bubble chrome.
- Final response renders as a clean text block with code-copy support and artifact action area.
- Normal chat mode remains unchanged for non-agentic replies.
- New behavior is covered by focused tests for formatting/render gating.
</acceptance_criteria>
<implementation_plan>
1. Create chat-native agentic UI blocks (`AgentThinkingCard`, `AgentStepList`, `AgentSystemMessage`, `AgentFinalResponse`) and refactor `ForgeAgentBubble` to compose them.
2. Extend forgeagent types to support transcript-level system messages and artifact CTA metadata needed by the new UI.
3. Integrate agentic rendering into `ChatView` with conditional transcript blocks and Manus-like assistant presentation.
4. Add a Rust→Tauri event contract for plan and step progress; wire frontend listeners to update live agentic state.
5. Add targeted tests and update `.planning/STATE.md` / summary files after verification.
</implementation_plan>
<verification>
- `pnpm exec vitest run` for the new/updated agentic tests
- targeted Rust build/test for event contract if touched
- manual `pnpm tauri dev` verification of agentic transcript layout
</verification>
@@ -0,0 +1,49 @@
---
phase: 06-chat-ui-redesign
plan: 04
status: complete
completed_at: "2026-04-02T12:20:00Z"
---
# Plan 06-04 Summary: Agentic Manus Conversation Blocks
## Completed
- Added chat-native agentic UI blocks:
- `AgentThinkingCard`
- `AgentStepList`
- `AgentSystemMessage`
- `AgentFinalResponse`
- Refactored `ForgeAgentBubble` to compose the new Manus-style sections instead of the older heavy card layout.
- Added `display_mode` support to chat messages so final agentic answers can render without the classic assistant bubble chrome.
- Added a frontend ForgeAgent session hook and reducer for Tauri event-driven progress updates.
- Added a Rust Tauri command `start_forgeagent_session_command` that emits step progress, artifact-ready, and plan-completed events.
- Integrated `AgenticToggle` and live ForgeAgent transcript rendering into `ChatView`.
## Verification
### Frontend tests
```bash
pnpm exec vitest run src/lib/chat.test.ts src/lib/chatDebug.test.ts src/components/ChatView.debug.test.tsx src/lib/forgeagent-state.test.ts src/components/forgeagent/ForgeAgentBubble.test.tsx src/components/MessageBubble.test.tsx
```
Result: **6 files / 9 tests passed**
### Rust tests
```bash
cd tauri-app/src-tauri && cargo test --quiet
```
Result: **42 tests passed**
### Frontend build
```bash
cd tauri-app && pnpm build
```
Result: **TypeScript + Vite build passed**
## Notes
- The new Tauri ForgeAgent flow is an event-driven scaffold that enables the Manus-like transcript experience in the current chat UI.
- Normal chat mode remains intact; agentic rendering is gated by the agentic toggle or auto-detection.
@@ -0,0 +1,51 @@
# Phase 6: Chat UI Redesign - Context
**Gathered:** 2026-04-02
**Status:** Ready for planning
## Phase Boundary
The existing milestone already moved ForgeLM toward Manus-inspired colors and input composition, but the key agentic transcript experience is still missing. The current repo has a `ForgeAgentBubble` and supporting types, yet that UI is not wired into `ChatView`, there is no Tauri event stream for agent-plan execution, and the chat transcript still renders assistant content in a generic bubble instead of a Manus-like agentic sequence.
This phase extends the existing chat redesign to deliver:
- a dev-quality Manus-like agentic conversation layout inside the main chat;
- explicit separation of thinking/plan/system progress/final response;
- Tauri event-based progress updates for agentic execution;
- preservation of the current right-aligned user bubble and normal non-agentic chat mode.
## Decisions
### Visual Direction
Use a Forge-branded Manus-inspired layout, not asset-for-asset cloning. Preserve hierarchy, density, spacing, and interaction style.
### Technical Direction
Reuse existing `types/forgeagent.ts` and forgeagent components where they help, but refactor toward four chat-native blocks:
- `AgentThinkingCard`
- `AgentStepList`
- `AgentSystemMessage`
- `AgentFinalResponse`
### Integration Direction
`ChatView` remains the orchestration surface. Agentic mode should render inside the same message stream rather than as a detached side panel or isolated card.
## Existing Code Insights
- `ChatView.tsx` owns message rendering, streaming state, and persistence.
- `ForgeAgentBubble.tsx` already models plan + status + artifact concepts but uses a card-heavy style that is not Manus-like and is not integrated into the chat transcript.
- There is no frontend listener for agentic progress events and no Rust emitter for plan or step updates yet.
- `types/forgeagent.ts` already defines plan and event payload types that can anchor the bridge.
## Specific Ideas
1. Add a fourth plan (`06-04`) rather than rewriting the earlier phase docs.
2. Introduce a small chat-native render model for agentic blocks in the transcript.
3. Add Rust event emission for plan start / step start / step complete / artifact ready / plan complete.
4. Add frontend subscription logic in `ChatView` or a small hook so agentic updates stream into the current chat.
5. Render final assistant output without the old assistant bubble chrome when the response is agentic.
## Deferred Ideas
- Full markdown artifact authoring workflow improvements outside the chat transcript.
- Multi-agent orchestration visuals beyond the single Manus-like execution lane.