feat: improve chat ui messages (#132)

This commit is contained in:
Carlos Florêncio
2026-01-31 19:45:33 +00:00
committed by GitHub
parent ff4e0779d2
commit 6d23d68633
80 changed files with 4609 additions and 1470 deletions
+4
View File
@@ -79,3 +79,7 @@ node_modules/
# TypeScript
*.tsbuildinfo
apps/landing/next-env.d.ts
# agent message logs
raw-*.jsonl
normalized-*.jsonl
+58 -6
View File
@@ -237,7 +237,8 @@ func (a *orchestratorAdapter) ResumeTaskSession(ctx context.Context, taskID, tas
// messageCreatorAdapter adapts the task service to the orchestrator.MessageCreator interface
type messageCreatorAdapter struct {
svc *taskservice.Service
svc *taskservice.Service
logger *logger.Logger
}
// CreateAgentMessage creates a message with author_type="agent"
@@ -264,33 +265,84 @@ func (a *messageCreatorAdapter) CreateUserMessage(ctx context.Context, taskID, c
return err
}
// toolKindToMessageType maps the normalized tool kind to a frontend message type.
// This allows the frontend to use specialized renderers for different tool categories.
// Returns the message type and whether a warning should be logged (for unknown kinds).
func toolKindToMessageType(kind streams.ToolKind) (string, bool) {
switch kind {
case streams.ToolKindReadFile:
return "tool_read", false
case streams.ToolKindCodeSearch:
return "tool_search", false
case streams.ToolKindModifyFile:
return "tool_edit", false
case streams.ToolKindShellExec:
return "tool_execute", false
case streams.ToolKindHttpRequest:
return "tool_call", false
case streams.ToolKindGeneric:
return "tool_call", false
case streams.ToolKindCreateTask:
return "tool_call", false
case streams.ToolKindSubagentTask:
return "tool_call", false
case streams.ToolKindShowPlan:
return "tool_call", false
case streams.ToolKindManageTodos:
return "todo", false
case streams.ToolKindMisc:
return "tool_call", false
default:
// Unknown kind - this shouldn't happen, log a warning
return "tool_call", true
}
}
// CreateToolCallMessage creates a message for a tool call
func (a *messageCreatorAdapter) CreateToolCallMessage(ctx context.Context, taskID, toolCallID, title, status, agentSessionID, turnID string, normalized *streams.NormalizedPayload) error {
func (a *messageCreatorAdapter) CreateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, title, status, agentSessionID, turnID string, normalized *streams.NormalizedPayload) error {
metadata := map[string]interface{}{
"tool_call_id": toolCallID,
"title": title,
"status": status,
}
// Add parent tool call ID for subagent nesting (if present)
if parentToolCallID != "" {
metadata["parent_tool_call_id"] = parentToolCallID
}
// Add normalized tool data to metadata for frontend consumption
if normalized != nil {
metadata["normalized"] = normalized
}
// Determine message type from the normalized tool kind
msgType := "tool_call"
if normalized != nil {
var warn bool
msgType, warn = toolKindToMessageType(normalized.Kind())
if warn {
a.logger.Warn("unknown tool kind falling back to tool_call",
zap.String("kind", string(normalized.Kind())),
zap.String("tool_call_id", toolCallID),
zap.String("title", title))
}
}
_, err := a.svc.CreateMessage(ctx, &taskservice.CreateMessageRequest{
TaskSessionID: agentSessionID,
TaskID: taskID,
TurnID: turnID,
Content: title,
AuthorType: "agent",
Type: "tool_call",
Type: msgType,
Metadata: metadata,
})
return err
}
// UpdateToolCallMessage updates a tool call message's status
func (a *messageCreatorAdapter) UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, status, result, agentSessionID, title string, normalized *streams.NormalizedPayload) error {
return a.svc.UpdateToolCallMessage(ctx, agentSessionID, toolCallID, status, result, title, normalized)
// UpdateToolCallMessage updates a tool call message's status.
// If the message doesn't exist, it creates it using taskID, turnID, and msgType.
func (a *messageCreatorAdapter) UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, status, result, agentSessionID, title, turnID, msgType string, normalized *streams.NormalizedPayload) error {
return a.svc.UpdateToolCallMessageWithCreate(ctx, agentSessionID, toolCallID, parentToolCallID, status, result, title, normalized, taskID, turnID, msgType)
}
// CreateSessionMessage creates a message for non-chat session updates (status/progress/error/etc).
+5 -26
View File
@@ -36,7 +36,6 @@ import (
editorhandlers "github.com/kandev/kandev/internal/editors/handlers"
notificationcontroller "github.com/kandev/kandev/internal/notifications/controller"
notificationhandlers "github.com/kandev/kandev/internal/notifications/handlers"
notificationservice "github.com/kandev/kandev/internal/notifications/service"
promptcontroller "github.com/kandev/kandev/internal/prompts/controller"
prompthandlers "github.com/kandev/kandev/internal/prompts/handlers"
@@ -199,7 +198,7 @@ func main() {
log.Info("Task Service initialized")
userCtrl := usercontroller.NewController(userSvc)
var notificationSvc *notificationservice.Service
var gateway *gateways.Gateway
var notificationCtrl *notificationcontroller.Controller
editorCtrl := editorcontroller.NewController(editorSvc)
promptCtrl := promptcontroller.NewController(promptSvc)
@@ -278,7 +277,7 @@ func main() {
// WEBSOCKET GATEWAY (All communication via WebSocket)
// ============================================
log.Info("Initializing WebSocket Gateway...")
gateway, _, _, err := provideGateway(
gateway, _, notificationCtrl, err = provideGateway(
ctx,
log,
eventBus,
@@ -294,31 +293,11 @@ func main() {
log.Fatal("Failed to initialize WebSocket gateway", zap.Error(err))
}
// Start the WebSocket hub
go gateway.Hub.Run(ctx)
gateways.RegisterTaskNotifications(ctx, eventBus, gateway.Hub, log)
gateways.RegisterUserNotifications(ctx, eventBus, gateway.Hub, log)
// Note: Hub is started and TaskNotifications/UserNotifications/TaskSessionStateChanged
// are already registered by provideGateway.
// Only register SessionStreamNotifications here as it's not part of provideGateway
gateways.RegisterSessionStreamNotifications(ctx, eventBus, gateway.Hub, log)
notificationSvc = notificationservice.NewService(notificationRepo, taskRepo, gateway.Hub, log)
notificationCtrl = notificationcontroller.NewController(notificationSvc)
if eventBus != nil {
_, err = eventBus.Subscribe(events.TaskSessionStateChanged, func(ctx context.Context, event *bus.Event) error {
data, ok := event.Data.(map[string]interface{})
if !ok {
return nil
}
taskID, _ := data["task_id"].(string)
sessionID, _ := data["session_id"].(string)
newState, _ := data["new_state"].(string)
notificationSvc.HandleTaskSessionStateChanged(ctx, taskID, sessionID, newState)
return nil
})
if err != nil {
log.Error("Failed to subscribe to task session notifications", zap.Error(err))
}
}
// Set up session data provider for session subscriptions
// Sends initial git status when a client subscribes to a session
gateway.Hub.SetSessionDataProvider(func(ctx context.Context, sessionID string) ([]*ws.Message, error) {
+1 -1
View File
@@ -36,7 +36,7 @@ func provideOrchestrator(
orchestratorSvc := orchestrator.NewService(serviceCfg, eventBus, agentManagerClient, taskRepoAdapter, taskRepo, userSvc, log)
taskSvc.SetExecutionStopper(orchestratorSvc)
msgCreator := &messageCreatorAdapter{svc: taskSvc}
msgCreator := &messageCreatorAdapter{svc: taskSvc, logger: log}
orchestratorSvc.SetMessageCreator(msgCreator)
orchestratorSvc.SetTurnService(newTurnServiceAdapter(taskSvc))
@@ -0,0 +1,325 @@
# Debugging Tool Normalization Issues
This guide explains how to debug and fix issues where tool calls from agents are not rendering correctly in the frontend (e.g., a shell command showing as generic `tool_call` instead of `tool_execute`).
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Tool Call Normalization Flow │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ Agent CLI Adapter Lifecycle Orchestrator │
│ ┌────────┐ ┌──────────┐ ┌─────────┐ ┌────────────┐ │
│ │ Codex │──JSON──│ Codex │──Event──│ Manager │──Event──│ Event │ │
│ │ Claude │ │ Adapter │ │ │ │ Handlers │ │
│ │ etc. │ └────┬─────┘ └────┬────┘ └─────┬──────┘ │
│ └────────┘ │ │ │ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ NormalizedPayload AgentEvent Message DB │
│ ┌─────────────┐ ┌──────────┐ ┌──────────┐ │
│ │ kind: ... │ ───▶ │Normalized│ ──────▶│type: ... │ │
│ │ shell_exec │ │Payload │ │tool_exec │ │
│ └─────────────┘ └──────────┘ └────┬─────┘ │
│ │ │
│ ▼ │
│ WebSocket Event │
│ ┌──────────────┐ │
│ │type:tool_exec│ │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ Frontend │
│ ┌──────────────┐ │
│ │ToolExecute │ │
│ │ Message.tsx │ │
│ └──────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
## Key Files
| Layer | File | Purpose |
|-------|------|---------|
| Types | `internal/agentctl/types/streams/tool_payload.go` | `NormalizedPayload` struct and factory functions |
| Codex Adapter | `internal/agentctl/server/adapter/transport/codex/adapter.go` | Converts Codex events to `AgentEvent` |
| Codex Normalizer | `internal/agentctl/server/adapter/transport/codex/normalize.go` | Creates `NormalizedPayload` for Codex tools |
| StreamJSON Adapter | `internal/agentctl/server/adapter/transport/streamjson/adapter.go` | Converts Claude Code events to `AgentEvent` |
| StreamJSON Normalizer | `internal/agentctl/server/adapter/transport/streamjson/normalize.go` | Creates `NormalizedPayload` for Claude tools |
| OpenCode Normalizer | `internal/agentctl/server/adapter/transport/opencode/normalize.go` | Creates `NormalizedPayload` for OpenCode tools |
| Lifecycle Events | `internal/agent/lifecycle/events.go` | Publishes `AgentStreamEvent` to event bus |
| Orchestrator Handlers | `internal/orchestrator/event_handlers.go` | Handles events and creates DB messages |
| Message Creator | `cmd/kandev/adapters.go` | `toolKindToMessageType()` maps kind to message type |
| Frontend Renderer | `apps/web/components/task/chat/message-renderer.tsx` | Routes message types to components |
## Tool Kind to Message Type Mapping
The `NormalizedPayload.Kind()` determines which frontend component renders the tool:
| Tool Kind | Message Type | Frontend Component |
|-----------|-------------|-------------------|
| `read_file` | `tool_read` | `ToolReadMessage` |
| `code_search` | `tool_search` | `ToolSearchMessage` |
| `modify_file` | `tool_edit` | `ToolEditMessage` |
| `shell_exec` | `tool_execute` | `ToolExecuteMessage` |
| `manage_todos` | `todo` | `TodoMessage` |
| `subagent_task` | `tool_call` | `ToolSubagentMessage` |
| `generic` | `tool_call` | `ToolCallMessage` |
| (nil/unknown) | `tool_call` | `ToolCallMessage` |
## Debugging Steps
### 1. Check Raw Events
Raw events are logged to `raw-<protocol>-<agent>.jsonl` files in the backend directory:
```bash
# View raw Codex events
tail -f raw-codex-codex.jsonl | jq .
# View raw Claude events
tail -f raw-streamjson-claude.jsonl | jq .
```
### 2. Check Normalized Events
Normalized events show what the adapter produced:
```bash
# View normalized events
tail -f normalized-codex-codex.jsonl | jq .
```
Look for the `normalized` field in `tool_call` events:
```json
{
"event": {
"type": "tool_call",
"normalized": {
"kind": "shell_exec",
"shell_exec": {
"command": "ls -la",
"work_dir": "/path/to/dir"
}
}
}
}
```
If `normalized` is missing or `kind` is wrong, the issue is in the adapter.
### 3. Check Database Message Type
Query the database to see what message type was stored:
```sql
SELECT id, type, metadata->>'normalized' as normalized
FROM task_session_messages
WHERE metadata->>'tool_call_id' = '<tool_call_id>'
ORDER BY created_at DESC LIMIT 1;
```
If the type is `tool_call` but should be `tool_execute`, the issue is in the message creation flow.
### 4. Check WebSocket Events
Use browser DevTools Network tab to inspect WebSocket messages. Look for `session.message.added` events and check the `type` field.
## Common Issues
### Issue 1: Missing NormalizedPayload in tool_update Events
**Symptom:** Tool calls render as generic `tool_call` instead of specialized type.
**Cause:** The adapter sends `tool_update` events (e.g., on completion) without the `NormalizedPayload`. When there's a race condition and the message doesn't exist yet, the fallback creation uses `tool_call` as default.
**Example (Codex):**
```go
// BAD - tool_update without normalized payload
update := AgentEvent{
Type: streams.EventTypeToolUpdate,
ToolCallID: p.Item.ID,
ToolStatus: "complete",
}
// GOOD - tool_update with normalized payload
update := AgentEvent{
Type: streams.EventTypeToolUpdate,
ToolCallID: p.Item.ID,
ToolStatus: "complete",
NormalizedPayload: a.normalizer.NormalizeToolCall("commandExecution", args),
}
```
**Fix Location:** Adapter's notification handler (e.g., `NotifyItemCompleted` in Codex adapter).
### Issue 2: Wrong Tool Name Passed to Normalizer
**Symptom:** Tool renders as `tool_call` (generic) instead of specialized type.
**Cause:** The normalizer's switch statement doesn't match the tool name.
**Example:**
```go
// Normalizer expects "commandExecution" but receives "command_execution"
switch toolName {
case CodexItemCommandExecution: // "commandExecution"
return n.normalizeCommand(args)
default:
return n.normalizeGeneric(toolName, args) // Falls through here
}
```
**Fix:** Check the exact tool name string in the protocol and match it in the normalizer.
### Issue 3: Factory Function Not Setting Kind
**Symptom:** `normalized.Kind()` returns empty or wrong value.
**Cause:** Factory function doesn't set the `kind` field correctly.
**Example:**
```go
// BAD - missing kind
func NewShellExec(...) *NormalizedPayload {
return &NormalizedPayload{
shellExec: &ShellExecPayload{...},
}
}
// GOOD - kind is set
func NewShellExec(...) *NormalizedPayload {
return &NormalizedPayload{
kind: ToolKindShellExec,
shellExec: &ShellExecPayload{...},
}
}
```
**Fix Location:** `internal/agentctl/types/streams/tool_payload.go`
### Issue 4: toolKindToMessageType Not Handling New Kind
**Symptom:** New tool kind renders as generic `tool_call`.
**Cause:** The `toolKindToMessageType` function doesn't have a case for the new kind.
**Fix Location:** Two places need updating:
1. `internal/orchestrator/event_handlers.go` - `toolKindToMessageType()`
2. `cmd/kandev/adapters.go` - `toolKindToMessageType()`
### Issue 5: Missing UnmarshalJSON for NormalizedPayload
**Symptom:** All tool calls render as `tool_call` even though adapter logs show correct `kind`.
**Cause:** The `NormalizedPayload` struct has unexported fields. Without a custom `UnmarshalJSON` method, the standard library cannot populate these fields when deserializing events from WebSocket/JSON.
**Example:**
```go
// NormalizedPayload with unexported fields requires both methods:
func (p *NormalizedPayload) MarshalJSON() ([]byte, error) { ... }
func (p *NormalizedPayload) UnmarshalJSON(data []byte) error { ... } // REQUIRED!
```
**Fix Location:** `internal/agentctl/types/streams/tool_payload.go`
**How to verify:** Run the round-trip test:
```bash
go test ./internal/agentctl/types/streams/... -v -run MarshalRoundTrip
```
## Adding a New Tool Kind
1. **Add kind constant** in `internal/agentctl/types/streams/tool_payload.go`:
```go
const (
ToolKindMyNewTool ToolKind = "my_new_tool"
)
```
2. **Add payload struct** with fields:
```go
type MyNewToolPayload struct {
SomeField string `json:"some_field"`
}
```
3. **Add unexported field** to `NormalizedPayload`:
```go
type NormalizedPayload struct {
kind ToolKind
myNewTool *MyNewToolPayload
// ...
}
```
4. **Add getter method**:
```go
func (p *NormalizedPayload) MyNewTool() *MyNewToolPayload { return p.myNewTool }
```
5. **Add to MarshalJSON**:
```go
type jsonPayload struct {
MyNewTool *MyNewToolPayload `json:"my_new_tool,omitempty"`
// ...
}
```
6. **Add factory function**:
```go
func NewMyNewTool(someField string) *NormalizedPayload {
return &NormalizedPayload{
kind: ToolKindMyNewTool,
myNewTool: &MyNewToolPayload{
SomeField: someField,
},
}
}
```
7. **Update normalizers** in each adapter to call the factory function.
8. **Update toolKindToMessageType** in both locations:
```go
case streams.ToolKindMyNewTool:
return "tool_my_new"
```
9. **Add frontend component** and update `message-renderer.tsx`:
```tsx
{
matches: (comment) => comment.type === 'tool_my_new',
render: (comment) => <ToolMyNewMessage comment={comment} />,
},
```
## Testing
### Unit Tests
Run normalizer tests:
```bash
go test ./internal/agentctl/server/adapter/transport/streamjson/... -v
go test ./internal/agentctl/server/adapter/transport/codex/... -v
```
### Integration Testing
1. Start a session with the agent
2. Trigger the tool you're testing
3. Check normalized events file
4. Check database message type
5. Verify frontend renders correct component
## Checklist for Fixing Normalization Issues
- [ ] Check raw events to confirm agent sends expected data
- [ ] Check normalized events to confirm adapter produces correct payload
- [ ] Verify `NormalizedPayload.Kind()` returns correct kind
- [ ] Verify `tool_call` event includes `NormalizedPayload`
- [ ] Verify `tool_update` event includes `NormalizedPayload` (for race condition handling)
- [ ] Check `toolKindToMessageType` handles the kind in both files
- [ ] Verify database stores correct message type
- [ ] Verify frontend `message-renderer.tsx` has matching adapter
@@ -50,6 +50,10 @@ type AgentStreamEventData struct {
SessionStatus string `json:"session_status,omitempty"` // "resumed" or "new" for session_status events
Data interface{} `json:"data,omitempty"`
// ParentToolCallID identifies the parent Task tool call when this event
// comes from a subagent. Used for visual nesting in the UI.
ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
// Normalized contains the typed tool payload data.
// This is used to populate message metadata with structured tool information.
Normalized *streams.NormalizedPayload `json:"normalized,omitempty"`
+12 -11
View File
@@ -115,17 +115,18 @@ func (p *EventPublisher) PublishAgentStreamEvent(execution *AgentExecution, even
// Build the nested event data
// event.SessionID is the ACP session ID (internal agent protocol session)
eventData := &AgentStreamEventData{
Type: event.Type,
ACPSessionID: event.SessionID,
Text: event.Text,
ToolCallID: event.ToolCallID,
ToolName: event.ToolName,
ToolTitle: event.ToolTitle,
ToolStatus: event.ToolStatus,
Error: event.Error,
SessionStatus: event.SessionStatus,
Data: event.Data,
Normalized: event.NormalizedPayload,
Type: event.Type,
ACPSessionID: event.SessionID,
Text: event.Text,
ToolCallID: event.ToolCallID,
ParentToolCallID: event.ParentToolCallID,
ToolName: event.ToolName,
ToolTitle: event.ToolTitle,
ToolStatus: event.ToolStatus,
Error: event.Error,
SessionStatus: event.SessionStatus,
Data: event.Data,
Normalized: event.NormalizedPayload,
}
// Build agent event message payload
@@ -13,7 +13,7 @@
"cmd": [
"npx",
"-y",
"@augmentcode/auggie@0.14.0",
"@augmentcode/auggie@0.15.0",
"--acp"
],
"passthrough_config": {
@@ -688,7 +688,10 @@
},
"model_config": {
"default_model": "anthropic/claude-sonnet-4-20250514",
"dynamic_models_cmd": ["opencode", "models"],
"dynamic_models_cmd": [
"opencode",
"models"
],
"dynamic_models_timeout_ms": 30000,
"available_models": [
{
@@ -72,6 +72,10 @@ type Adapter struct {
// When set, this context will be prepended to the first prompt sent to the session.
pendingContext string
// Tool call tracking for result normalization
// Maps toolCallId -> NormalizedPayload so we can update with results
activeToolCalls map[string]*streams.NormalizedPayload
// Synchronization
mu sync.RWMutex
closed bool
@@ -82,11 +86,12 @@ type Adapter struct {
// cfg.AgentID is required for debug file naming.
func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter {
return &Adapter{
cfg: cfg,
logger: log.WithFields(zap.String("adapter", "acp"), zap.String("agent_id", cfg.AgentID)),
agentID: cfg.AgentID,
normalizer: NewNormalizer(),
updatesCh: make(chan AgentEvent, 100),
cfg: cfg,
logger: log.WithFields(zap.String("adapter", "acp"), zap.String("agent_id", cfg.AgentID)),
agentID: cfg.AgentID,
normalizer: NewNormalizer(),
updatesCh: make(chan AgentEvent, 100),
activeToolCalls: make(map[string]*streams.NormalizedPayload),
}
}
@@ -446,6 +451,12 @@ func (a *Adapter) convertNotification(n acp.SessionNotification) *AgentEvent {
toolKind := string(u.ToolCall.Kind)
normalizedPayload := a.normalizer.NormalizeToolCall(toolKind, args)
// Store the payload for later result updates
toolCallID := string(u.ToolCall.ToolCallId)
a.mu.Lock()
a.activeToolCalls[toolCallID] = normalizedPayload
a.mu.Unlock()
// Detect tool type for logging
toolType := DetectToolOperationType(toolKind, args)
_ = toolType // Used for normalization
@@ -459,7 +470,7 @@ func (a *Adapter) convertNotification(n acp.SessionNotification) *AgentEvent {
return &AgentEvent{
Type: streams.EventTypeToolCall,
SessionID: string(n.SessionId),
ToolCallID: string(u.ToolCall.ToolCallId),
ToolCallID: toolCallID,
ToolName: string(u.ToolCall.Kind), // Kind is effectively the tool name
ToolTitle: u.ToolCall.Title,
ToolStatus: status,
@@ -467,6 +478,7 @@ func (a *Adapter) convertNotification(n acp.SessionNotification) *AgentEvent {
}
case u.ToolCallUpdate != nil:
toolCallID := string(u.ToolCallUpdate.ToolCallId)
status := ""
if u.ToolCallUpdate.Status != nil {
status = string(*u.ToolCallUpdate.Status)
@@ -475,11 +487,35 @@ func (a *Adapter) convertNotification(n acp.SessionNotification) *AgentEvent {
if status == "completed" {
status = "complete"
}
// Look up the stored payload and update with result if we have rawOutput
var normalizedPayload *streams.NormalizedPayload
if u.ToolCallUpdate.RawOutput != nil {
a.mu.Lock()
if payload, ok := a.activeToolCalls[toolCallID]; ok {
// Update the payload with the result
a.normalizer.NormalizeToolResult(payload, u.ToolCallUpdate.RawOutput)
normalizedPayload = payload
// Clean up if completed
if status == "complete" || status == "error" {
delete(a.activeToolCalls, toolCallID)
}
}
a.mu.Unlock()
} else if status == "complete" || status == "error" {
// Clean up even without output
a.mu.Lock()
normalizedPayload = a.activeToolCalls[toolCallID]
delete(a.activeToolCalls, toolCallID)
a.mu.Unlock()
}
return &AgentEvent{
Type: streams.EventTypeToolUpdate,
SessionID: string(n.SessionId),
ToolCallID: string(u.ToolCallUpdate.ToolCallId),
ToolStatus: status,
Type: streams.EventTypeToolUpdate,
SessionID: string(n.SessionId),
ToolCallID: toolCallID,
ToolStatus: status,
NormalizedPayload: normalizedPayload,
}
case u.Plan != nil:
@@ -1,6 +1,7 @@
package acp
import (
"strconv"
"strings"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/shared"
@@ -16,6 +17,12 @@ func DetectToolOperationType(toolKind string, args map[string]any) string {
case "edit":
return "tool_edit"
case "read":
// Check if this is a directory read (file listing)
if rawInput, ok := args["raw_input"].(map[string]any); ok {
if readType, ok := rawInput["type"].(string); ok && readType == "directory" {
return "tool_search"
}
}
return "tool_read"
case "execute":
return "tool_execute"
@@ -30,6 +37,8 @@ func DetectToolOperationType(toolKind string, args map[string]any) string {
return "tool_read"
case "execute", "bash", "run":
return "tool_execute"
case "glob", "grep", "search":
return "tool_search"
default:
return "tool_call" // Generic fallback
}
@@ -67,18 +76,131 @@ func (n *Normalizer) NormalizeToolCall(toolName string, args map[string]any) *st
// NormalizeToolResult updates the payload with tool result data.
func (n *Normalizer) NormalizeToolResult(payload *streams.NormalizedPayload, result any) {
switch payload.Kind {
// Extract rawOutput.output if result is wrapped
output := extractRawOutput(result)
switch payload.Kind() {
case streams.ToolKindReadFile:
if payload.ReadFile() != nil && output != "" {
lines := strings.Count(output, "\n")
if !strings.HasSuffix(output, "\n") && len(output) > 0 {
lines++ // Count the last line if it doesn't end with newline
}
payload.ReadFile().Output = &streams.ReadFileOutput{
Content: output,
LineCount: lines,
}
}
case streams.ToolKindCodeSearch:
if payload.CodeSearch() != nil && output != "" {
// Parse output as file listing (one file per line)
files := parseFileList(output)
payload.CodeSearch().Output = &streams.CodeSearchOutput{
Files: files,
FileCount: len(files),
}
}
case streams.ToolKindShellExec:
if payload.ShellExec != nil {
shared.NormalizeShellResult(payload.ShellExec, result)
if payload.ShellExec() != nil && output != "" {
// Parse ACP's XML-like shell output format
exitCode, stdout, stderr := parseShellOutput(output)
payload.ShellExec().Output = &streams.ShellExecOutput{
ExitCode: exitCode,
Stdout: stdout,
Stderr: stderr,
}
}
case streams.ToolKindGeneric:
if payload.Generic != nil {
payload.Generic.Output = result
if payload.Generic() != nil {
payload.Generic().Output = result
}
}
}
// extractRawOutput gets the output string from ACP result data.
// ACP wraps results in {"rawOutput": {"output": "..."}}
func extractRawOutput(result any) string {
if result == nil {
return ""
}
// Try direct string
if s, ok := result.(string); ok {
return s
}
// Try rawOutput.output pattern
resultMap, ok := result.(map[string]any)
if !ok {
return ""
}
// Check for rawOutput wrapper
if rawOutput, ok := resultMap["rawOutput"].(map[string]any); ok {
if output, ok := rawOutput["output"].(string); ok {
return output
}
}
// Check for direct output field
if output, ok := resultMap["output"].(string); ok {
return output
}
return ""
}
// parseFileList parses a newline-separated file listing into a slice of paths.
func parseFileList(output string) []string {
var files []string
for _, line := range strings.Split(output, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Skip header lines that don't look like paths
if strings.HasPrefix(line, "Here's") || strings.HasPrefix(line, "Files") {
continue
}
files = append(files, line)
}
return files
}
// parseShellOutput parses ACP's XML-like shell output format.
// Format: "...<return-code>N</return-code>...<output>...</output>..."
// Returns exit code, stdout, and stderr (stderr from <stderr> tag if present).
func parseShellOutput(output string) (exitCode int, stdout, stderr string) {
// Extract return code
if start := strings.Index(output, "<return-code>"); start != -1 {
start += len("<return-code>")
if end := strings.Index(output[start:], "</return-code>"); end != -1 {
codeStr := strings.TrimSpace(output[start : start+end])
if code, err := strconv.Atoi(codeStr); err == nil {
exitCode = code
}
}
}
// Extract stdout from <output> tag
if start := strings.Index(output, "<output>"); start != -1 {
start += len("<output>")
if end := strings.Index(output[start:], "</output>"); end != -1 {
stdout = strings.TrimSpace(output[start : start+end])
}
}
// Extract stderr from <stderr> tag if present
if start := strings.Index(output, "<stderr>"); start != -1 {
start += len("<stderr>")
if end := strings.Index(output[start:], "</stderr>"); end != -1 {
stderr = strings.TrimSpace(output[start : start+end])
}
}
return exitCode, stdout, stderr
}
// normalizeEdit converts ACP edit tool data.
func (n *Normalizer) normalizeEdit(args map[string]any) *streams.NormalizedPayload {
rawInput, _ := args["raw_input"].(map[string]any)
@@ -92,17 +214,11 @@ func (n *Normalizer) normalizeEdit(args map[string]any) *streams.NormalizedPaylo
path = extractPathFromLocations(args)
}
payload := &streams.NormalizedPayload{
Kind: streams.ToolKindModifyFile,
ModifyFile: &streams.ModifyFilePayload{
FilePath: path,
Mutations: []streams.FileMutation{},
},
}
var mutations []streams.FileMutation
// Check if this is file creation (has file_content) vs str_replace
if fileContent, ok := rawInput["file_content"].(string); ok {
payload.ModifyFile.Mutations = append(payload.ModifyFile.Mutations, streams.FileMutation{
mutations = append(mutations, streams.FileMutation{
Type: streams.MutationCreate,
Content: fileContent,
})
@@ -130,13 +246,15 @@ func (n *Normalizer) normalizeEdit(args map[string]any) *streams.NormalizedPaylo
mutation.Diff = shared.GenerateUnifiedDiff(oldStr, newStr, path, mutation.StartLine)
}
payload.ModifyFile.Mutations = append(payload.ModifyFile.Mutations, mutation)
mutations = append(mutations, mutation)
}
return payload
// Use factory function
return streams.NewModifyFile(path, mutations)
}
// normalizeRead converts ACP read tool data.
// If rawInput.type is "directory", this becomes a code search (file listing) operation.
func (n *Normalizer) normalizeRead(args map[string]any) *streams.NormalizedPayload {
rawInput, _ := args["raw_input"].(map[string]any)
if rawInput == nil {
@@ -148,6 +266,11 @@ func (n *Normalizer) normalizeRead(args map[string]any) *streams.NormalizedPaylo
path = extractPathFromLocations(args)
}
// Check if this is a directory read - treat as code search (file listing)
if readType := shared.GetString(rawInput, "type"); readType == "directory" {
return streams.NewCodeSearch("", "", path, "")
}
return streams.NewReadFile(path, 0, 0)
}
@@ -32,16 +32,24 @@ func TestACPNormalization(t *testing.T) {
// Verify the Kind is set correctly based on tool type
switch toolType {
case "tool_edit":
if payload.Kind != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, payload.Kind)
if payload.Kind() != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, payload.Kind())
}
case "tool_read":
if payload.Kind != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, payload.Kind)
if payload.Kind() != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, payload.Kind())
}
case "tool_execute":
if payload.Kind != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, payload.Kind)
if payload.Kind() != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, payload.Kind())
}
case "tool_search":
if payload.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, payload.Kind())
}
case "tool_call":
if payload.Kind() != streams.ToolKindGeneric {
t.Errorf("expected Kind %q, got %q", streams.ToolKindGeneric, payload.Kind())
}
}
})
@@ -105,9 +113,15 @@ func TestDetectToolOperationType(t *testing.T) {
want: "tool_execute",
},
{
name: "unknown kind falls back to tool_call",
name: "search kind returns tool_search",
toolKind: "search",
args: map[string]any{"kind": "search"},
want: "tool_search",
},
{
name: "unknown kind falls back to tool_call",
toolKind: "custom_tool",
args: map[string]any{"kind": "custom_tool"},
want: "tool_call",
},
{
@@ -122,6 +136,17 @@ func TestDetectToolOperationType(t *testing.T) {
args: map[string]any{"kind": "edit"},
want: "tool_edit",
},
{
name: "read with directory type returns tool_search",
toolKind: "read",
args: map[string]any{
"kind": "read",
"raw_input": map[string]any{
"type": "directory",
},
},
want: "tool_search",
},
}
for _, tt := range tests {
@@ -246,19 +271,19 @@ func TestNormalizerEdit(t *testing.T) {
}
result := normalizer.NormalizeToolCall("edit", args)
if result.Kind != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind)
if result.Kind() != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind())
}
if result.ModifyFile == nil {
if result.ModifyFile() == nil {
t.Fatal("expected ModifyFile to be set")
}
if result.ModifyFile.FilePath != "file.ts" {
t.Errorf("expected FilePath 'file.ts', got %q", result.ModifyFile.FilePath)
if result.ModifyFile().FilePath != "file.ts" {
t.Errorf("expected FilePath 'file.ts', got %q", result.ModifyFile().FilePath)
}
if len(result.ModifyFile.Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile.Mutations))
if len(result.ModifyFile().Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile().Mutations))
}
mutation := result.ModifyFile.Mutations[0]
mutation := result.ModifyFile().Mutations[0]
if mutation.OldContent != "old code" {
t.Errorf("expected OldContent 'old code', got %q", mutation.OldContent)
}
@@ -287,8 +312,8 @@ func TestNormalizerEdit(t *testing.T) {
}
result := normalizer.NormalizeToolCall("edit", args)
if result.ModifyFile.FilePath != "/workspace/fallback.ts" {
t.Errorf("expected FilePath '/workspace/fallback.ts', got %q", result.ModifyFile.FilePath)
if result.ModifyFile().FilePath != "/workspace/fallback.ts" {
t.Errorf("expected FilePath '/workspace/fallback.ts', got %q", result.ModifyFile().FilePath)
}
})
}
@@ -305,14 +330,14 @@ func TestNormalizerRead(t *testing.T) {
},
}
result := normalizer.NormalizeToolCall("read", args)
if result.Kind != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, result.Kind)
if result.Kind() != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, result.Kind())
}
if result.ReadFile == nil {
if result.ReadFile() == nil {
t.Fatal("expected ReadFile to be set")
}
if result.ReadFile.FilePath != "config.json" {
t.Errorf("expected FilePath 'config.json', got %q", result.ReadFile.FilePath)
if result.ReadFile().FilePath != "config.json" {
t.Errorf("expected FilePath 'config.json', got %q", result.ReadFile().FilePath)
}
})
@@ -327,8 +352,133 @@ func TestNormalizerRead(t *testing.T) {
},
}
result := normalizer.NormalizeToolCall("read", args)
if result.ReadFile.FilePath != "/workspace/README.md" {
t.Errorf("expected FilePath '/workspace/README.md', got %q", result.ReadFile.FilePath)
if result.ReadFile().FilePath != "/workspace/README.md" {
t.Errorf("expected FilePath '/workspace/README.md', got %q", result.ReadFile().FilePath)
}
})
t.Run("directory type returns code search", func(t *testing.T) {
args := map[string]any{
"kind": "read",
"raw_input": map[string]any{
"path": ".",
"type": "directory",
},
}
result := normalizer.NormalizeToolCall("read", args)
if result.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind())
}
if result.CodeSearch() == nil {
t.Fatal("expected CodeSearch to be set")
}
if result.CodeSearch().Path != "." {
t.Errorf("expected Path '.', got %q", result.CodeSearch().Path)
}
})
}
// TestNormalizerResult tests the normalizer's result handling.
func TestNormalizerResult(t *testing.T) {
normalizer := NewNormalizer()
t.Run("handles read file result", func(t *testing.T) {
payload := normalizer.NormalizeToolCall("read", map[string]any{
"kind": "read",
"raw_input": map[string]any{
"path": "file.txt",
},
})
normalizer.NormalizeToolResult(payload, map[string]any{
"rawOutput": map[string]any{
"output": "line 1\nline 2\nline 3",
},
})
if payload.ReadFile().Output == nil {
t.Fatal("expected Output to be set")
}
if payload.ReadFile().Output.Content != "line 1\nline 2\nline 3" {
t.Errorf("expected Content, got %q", payload.ReadFile().Output.Content)
}
if payload.ReadFile().Output.LineCount != 3 {
t.Errorf("expected LineCount 3, got %d", payload.ReadFile().Output.LineCount)
}
})
t.Run("handles directory listing result", func(t *testing.T) {
payload := normalizer.NormalizeToolCall("read", map[string]any{
"kind": "read",
"raw_input": map[string]any{
"path": ".",
"type": "directory",
},
})
normalizer.NormalizeToolResult(payload, map[string]any{
"rawOutput": map[string]any{
"output": "Here's the files:\n./file1.ts\n./file2.go\n./src/main.ts",
},
})
if payload.CodeSearch().Output == nil {
t.Fatal("expected Output to be set")
}
// Should skip "Here's the files:" header
if payload.CodeSearch().Output.FileCount != 3 {
t.Errorf("expected FileCount 3, got %d", payload.CodeSearch().Output.FileCount)
}
})
t.Run("handles shell execution result", func(t *testing.T) {
payload := normalizer.NormalizeToolCall("execute", map[string]any{
"kind": "execute",
"raw_input": map[string]any{
"command": "pwd",
"cwd": ".",
},
})
normalizer.NormalizeToolResult(payload, map[string]any{
"rawOutput": map[string]any{
"output": "Here are the results from executing the command.\n<return-code>\n0\n</return-code>\n<output>\n/Users/cfl/project\n\n</output>",
},
})
if payload.ShellExec().Output == nil {
t.Fatal("expected Output to be set")
}
if payload.ShellExec().Output.ExitCode != 0 {
t.Errorf("expected ExitCode 0, got %d", payload.ShellExec().Output.ExitCode)
}
if payload.ShellExec().Output.Stdout != "/Users/cfl/project" {
t.Errorf("expected Stdout '/Users/cfl/project', got %q", payload.ShellExec().Output.Stdout)
}
})
t.Run("handles shell execution with stderr", func(t *testing.T) {
payload := normalizer.NormalizeToolCall("execute", map[string]any{
"kind": "execute",
"raw_input": map[string]any{
"command": "cat nonexistent",
},
})
normalizer.NormalizeToolResult(payload, map[string]any{
"rawOutput": map[string]any{
"output": "<return-code>\n1\n</return-code>\n<output>\n</output>\n<stderr>\ncat: nonexistent: No such file or directory\n</stderr>",
},
})
if payload.ShellExec().Output == nil {
t.Fatal("expected Output to be set")
}
if payload.ShellExec().Output.ExitCode != 1 {
t.Errorf("expected ExitCode 1, got %d", payload.ShellExec().Output.ExitCode)
}
if payload.ShellExec().Output.Stderr != "cat: nonexistent: No such file or directory" {
t.Errorf("expected Stderr, got %q", payload.ShellExec().Output.Stderr)
}
})
}
@@ -347,20 +497,20 @@ func TestNormalizerExecute(t *testing.T) {
},
}
result := normalizer.NormalizeToolCall("execute", args)
if result.Kind != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, result.Kind)
if result.Kind() != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, result.Kind())
}
if result.ShellExec == nil {
if result.ShellExec() == nil {
t.Fatal("expected ShellExec to be set")
}
if result.ShellExec.Command != "npm test" {
t.Errorf("expected Command 'npm test', got %q", result.ShellExec.Command)
if result.ShellExec().Command != "npm test" {
t.Errorf("expected Command 'npm test', got %q", result.ShellExec().Command)
}
if result.ShellExec.WorkDir != "/workspace" {
t.Errorf("expected WorkDir '/workspace', got %q", result.ShellExec.WorkDir)
if result.ShellExec().WorkDir != "/workspace" {
t.Errorf("expected WorkDir '/workspace', got %q", result.ShellExec().WorkDir)
}
if result.ShellExec.Timeout != 30 {
t.Errorf("expected Timeout 30, got %d", result.ShellExec.Timeout)
if result.ShellExec().Timeout != 30 {
t.Errorf("expected Timeout 30, got %d", result.ShellExec().Timeout)
}
})
@@ -373,7 +523,7 @@ func TestNormalizerExecute(t *testing.T) {
},
}
result := normalizer.NormalizeToolCall("execute", args)
if !result.ShellExec.Background {
if !result.ShellExec().Background {
t.Error("expected Background to be true when wait is false")
}
})
@@ -7,4 +7,6 @@
{"key":"execute","input":{"tool_name":"execute","args":{"kind":"execute","raw_input":{"command":"npm test","cwd":"/workspace","max_wait_seconds":30}}},"expected":{"tool_type":"tool_execute","command":"npm test","cwd":"/workspace","timeout":30}}
{"key":"execute:2","input":{"tool_name":"execute","args":{"kind":"execute","raw_input":{"command":"go build ./...","cwd":"","max_wait_seconds":0}}},"expected":{"tool_type":"tool_execute","command":"go build ./..."}}
{"key":"execute:3","input":{"tool_name":"execute","args":{"kind":"execute","raw_input":{"command":"ls -la","cwd":"/tmp","max_wait_seconds":10}}},"expected":{"tool_type":"tool_execute","command":"ls -la","cwd":"/tmp","timeout":10}}
{"key":"search","input":{"tool_name":"search","args":{"kind":"search","raw_input":{"query":"TODO"}}},"expected":{"tool_type":"tool_call"}}
{"key":"search","input":{"tool_name":"search","args":{"kind":"search","raw_input":{"query":"TODO"}}},"expected":{"tool_type":"tool_search"}}
{"key":"read:directory","input":{"tool_name":"read","args":{"kind":"read","raw_input":{"path":".","type":"directory"}}},"expected":{"tool_type":"tool_search","file_path":"."}}
{"key":"unknown","input":{"tool_name":"custom_tool","args":{"kind":"custom_tool","raw_input":{"foo":"bar"}}},"expected":{"tool_type":"tool_call"}}
@@ -79,8 +79,9 @@ type Adapter struct {
stderrProvider StderrProvider
// Accumulators for streaming content
messageBuffer string
reasoningBuffer string
messageBuffer string
reasoningBuffer string
currentReasoningItemID string // track current reasoning item for separator insertion
// Turn completion signaling
turnCompleteCh chan turnCompleteResult
@@ -388,6 +389,7 @@ func (a *Adapter) Prompt(ctx context.Context, message string) error {
// Reset accumulators for new turn
a.messageBuffer = ""
a.reasoningBuffer = ""
a.currentReasoningItemID = ""
// Create channel to wait for turn completion
a.turnCompleteCh = make(chan turnCompleteResult, 1)
a.mu.Unlock()
@@ -595,6 +597,11 @@ func (a *Adapter) handleNotification(method string, params json.RawMessage) {
return
}
a.mu.Lock()
// Add separator when switching to a new reasoning item
if p.ItemID != a.currentReasoningItemID && a.reasoningBuffer != "" {
a.reasoningBuffer += "\n\n"
}
a.currentReasoningItemID = p.ItemID
a.reasoningBuffer += p.Delta
a.mu.Unlock()
a.sendUpdate(AgentEvent{
@@ -613,6 +620,11 @@ func (a *Adapter) handleNotification(method string, params json.RawMessage) {
return
}
a.mu.Lock()
// Add separator when switching to a new reasoning item
if p.ItemID != a.currentReasoningItemID && a.reasoningBuffer != "" {
a.reasoningBuffer += "\n\n"
}
a.currentReasoningItemID = p.ItemID
a.reasoningBuffer += p.Delta
a.mu.Unlock()
a.sendUpdate(AgentEvent{
@@ -840,6 +852,30 @@ func (a *Adapter) handleNotification(method string, params json.RawMessage) {
ToolCallID: p.Item.ID,
ToolStatus: status,
}
// Include normalized payload for fallback message creation
// This ensures the correct message type is used if the message doesn't exist yet
switch p.Item.Type {
case "commandExecution":
args := map[string]any{
"command": p.Item.Command,
"cwd": p.Item.Cwd,
}
update.NormalizedPayload = a.normalizer.NormalizeToolCall("commandExecution", args)
case "fileChange":
changesArgs := make([]any, 0, len(p.Item.Changes))
for _, c := range p.Item.Changes {
changesArgs = append(changesArgs, map[string]any{
"path": c.Path,
"diff": c.Diff,
})
}
args := map[string]any{
"changes": changesArgs,
}
update.NormalizedPayload = a.normalizer.NormalizeToolCall("fileChange", args)
}
// Include diff for file changes
if p.Item.Type == "fileChange" && len(p.Item.Changes) > 0 {
var diffs []string
@@ -38,21 +38,21 @@ func (n *Normalizer) NormalizeToolCall(toolName string, args map[string]any) *st
// NormalizeToolResult updates the payload with tool result data.
func (n *Normalizer) NormalizeToolResult(payload *streams.NormalizedPayload, result any) {
switch payload.Kind {
switch payload.Kind() {
case streams.ToolKindShellExec:
if payload.ShellExec != nil {
n.normalizeCommandResult(payload.ShellExec, result)
if payload.ShellExec() != nil {
n.normalizeCommandResult(payload.ShellExec(), result)
}
case streams.ToolKindModifyFile:
// File changes are typically completed with a diff in the update
if payload.ModifyFile != nil && len(payload.ModifyFile.Mutations) > 0 {
if payload.ModifyFile() != nil && len(payload.ModifyFile().Mutations) > 0 {
if diffStr, ok := result.(string); ok && diffStr != "" {
payload.ModifyFile.Mutations[0].Diff = diffStr
payload.ModifyFile().Mutations[0].Diff = diffStr
}
}
case streams.ToolKindGeneric:
if payload.Generic != nil {
payload.Generic.Output = result
if payload.Generic() != nil {
payload.Generic().Output = result
}
}
}
@@ -62,13 +62,8 @@ func (n *Normalizer) normalizeCommand(args map[string]any) *streams.NormalizedPa
command := shared.GetString(args, "command")
workDir := shared.GetString(args, "cwd")
return &streams.NormalizedPayload{
Kind: streams.ToolKindShellExec,
ShellExec: &streams.ShellExecPayload{
Command: command,
WorkDir: workDir,
},
}
// Use factory function
return streams.NewShellExec(command, workDir, "", 0, false)
}
// normalizeFileChange converts Codex fileChange item data.
@@ -76,9 +71,8 @@ func (n *Normalizer) normalizeFileChange(args map[string]any) *streams.Normalize
// Codex sends changes as an array in the item
changes, _ := args["changes"].([]any)
payload := &streams.ModifyFilePayload{
Mutations: []streams.FileMutation{},
}
var filePath string
var mutations []streams.FileMutation
for _, change := range changes {
changeMap, ok := change.(map[string]any)
@@ -87,8 +81,8 @@ func (n *Normalizer) normalizeFileChange(args map[string]any) *streams.Normalize
}
path := shared.GetString(changeMap, "path")
if payload.FilePath == "" {
payload.FilePath = path
if filePath == "" {
filePath = path
}
mutation := streams.FileMutation{
@@ -100,33 +94,25 @@ func (n *Normalizer) normalizeFileChange(args map[string]any) *streams.Normalize
mutation.Diff = diff
}
payload.Mutations = append(payload.Mutations, mutation)
mutations = append(mutations, mutation)
}
// If no changes array, try single file fields
if len(payload.Mutations) == 0 {
path := shared.GetString(args, "path")
payload.FilePath = path
payload.Mutations = append(payload.Mutations, streams.FileMutation{
if len(mutations) == 0 {
filePath = shared.GetString(args, "path")
mutations = append(mutations, streams.FileMutation{
Type: streams.MutationPatch,
})
}
return &streams.NormalizedPayload{
Kind: streams.ToolKindModifyFile,
ModifyFile: payload,
}
// Use factory function
return streams.NewModifyFile(filePath, mutations)
}
// normalizeGeneric wraps unknown items as generic.
func (n *Normalizer) normalizeGeneric(toolName string, args map[string]any) *streams.NormalizedPayload {
return &streams.NormalizedPayload{
Kind: streams.ToolKindGeneric,
Generic: &streams.GenericPayload{
Name: toolName,
Input: args,
},
}
// Use factory function
return streams.NewGeneric(toolName, args)
}
// normalizeCommandResult updates command payload with result data.
@@ -714,18 +714,32 @@ func (a *Adapter) handleMessagePartUpdated(props json.RawMessage, sessionID, ope
status = state.Status
}
title := state.Title
if title == "" {
title = toolName
// Build ToolState for normalization (do this first so we can use input for title)
toolState := &ToolState{
Output: state.Output,
Title: state.Title,
}
var args map[string]any
if state.Input != nil {
_ = json.Unmarshal(state.Input, &args) // Ignore error - args are optional
toolState.Input = make(map[string]any)
_ = json.Unmarshal(state.Input, &toolState.Input) // Ignore error - input is optional
}
if state.Metadata != nil {
toolState.Metadata = make(map[string]any)
_ = json.Unmarshal(state.Metadata, &toolState.Metadata) // Ignore error - metadata is optional
}
// Generate normalized payload
normalizedPayload := a.normalizer.NormalizeToolCall(toolName, args)
normalizedPayload := a.normalizer.NormalizeToolCall(toolName, toolState)
// Determine title: prefer derived title (command/path), then state.Title, fallback to toolName
// For tools like bash, the command is more useful than the description
title := deriveToolTitle(toolName, toolState.Input)
if title == "" {
title = state.Title
}
if title == "" {
title = toolName
}
// Track if we've seen this tool call before
a.mu.Lock()
@@ -766,6 +780,37 @@ func (a *Adapter) handleMessagePartUpdated(props json.RawMessage, sessionID, ope
}
}
// deriveToolTitle derives a user-friendly title from tool input.
// Returns the most relevant field for display (e.g., command for bash, path for read).
func deriveToolTitle(toolName string, input map[string]any) string {
if input == nil {
return ""
}
switch toolName {
case OpenCodeToolBash:
// For bash, use the command
if cmd, ok := input["command"].(string); ok && cmd != "" {
return cmd
}
case OpenCodeToolGlob, OpenCodeToolGrep:
// For search tools, use the pattern
if pattern, ok := input["pattern"].(string); ok && pattern != "" {
return pattern
}
case OpenCodeToolRead, OpenCodeToolEdit:
// For file tools, use the path
if path, ok := input["path"].(string); ok && path != "" {
return path
}
if path, ok := input["file_path"].(string); ok && path != "" {
return path
}
}
return ""
}
// handleMessageUpdated processes message.updated events (for token tracking)
func (a *Adapter) handleMessageUpdated(props json.RawMessage, sessionID string) {
parsed, err := opencode.ParseMessageUpdated(props)
@@ -1,6 +1,8 @@
package opencode
import (
"strings"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/shared"
"github.com/kandev/kandev/internal/agentctl/types/streams"
)
@@ -17,6 +19,9 @@ const (
OpenCodeToolBash = "bash"
OpenCodeToolEdit = "edit"
OpenCodeToolWebFetch = "webfetch"
OpenCodeToolGlob = "glob"
OpenCodeToolGrep = "grep"
OpenCodeToolRead = "read"
)
// Normalizer converts OpenCode protocol tool data to NormalizedPayload.
@@ -27,65 +32,95 @@ func NewNormalizer() *Normalizer {
return &Normalizer{}
}
// ToolState contains the full tool state for normalization
type ToolState struct {
Input map[string]any
Output string
Metadata map[string]any
Title string
}
// NormalizeToolCall converts OpenCode tool call data to NormalizedPayload.
func (n *Normalizer) NormalizeToolCall(toolName string, args map[string]any) *streams.NormalizedPayload {
func (n *Normalizer) NormalizeToolCall(toolName string, state *ToolState) *streams.NormalizedPayload {
if state == nil {
state = &ToolState{}
}
if state.Input == nil {
state.Input = make(map[string]any)
}
// OpenCode tool names are typically lowercase
switch toolName {
case OpenCodeToolBash:
return n.normalizeBash(args)
return n.normalizeBash(state)
case OpenCodeToolEdit:
return n.normalizeEdit(args)
return n.normalizeEdit(state)
case OpenCodeToolWebFetch:
return n.normalizeWebFetch(args)
return n.normalizeWebFetch(state)
case OpenCodeToolGlob:
return n.normalizeGlob(state)
case OpenCodeToolGrep:
return n.normalizeGrep(state)
case OpenCodeToolRead:
return n.normalizeRead(state)
default:
return n.normalizeGeneric(toolName, args)
return n.normalizeGeneric(toolName, state)
}
}
// NormalizeToolResult updates the payload with tool result data.
// Deprecated: Result data is now handled in NormalizeToolCall via ToolState
func (n *Normalizer) NormalizeToolResult(payload *streams.NormalizedPayload, result any) {
switch payload.Kind {
// Keep for backwards compatibility but normalization now happens in NormalizeToolCall
switch payload.Kind() {
case streams.ToolKindShellExec:
if payload.ShellExec != nil {
n.normalizeBashResult(payload.ShellExec, result)
if payload.ShellExec() != nil && payload.ShellExec().Output == nil {
n.normalizeBashResult(payload.ShellExec(), result)
}
case streams.ToolKindHttpRequest:
if payload.HttpRequest != nil {
if payload.HttpRequest() != nil {
if r, ok := result.(string); ok {
payload.HttpRequest.Response = r
payload.HttpRequest().Response = r
}
}
case streams.ToolKindGeneric:
if payload.Generic != nil {
payload.Generic.Output = result
if payload.Generic() != nil && payload.Generic().Output == nil {
payload.Generic().Output = result
}
}
}
// normalizeBash converts OpenCode bash tool data.
func (n *Normalizer) normalizeBash(args map[string]any) *streams.NormalizedPayload {
command := shared.GetString(args, "command")
func (n *Normalizer) normalizeBash(state *ToolState) *streams.NormalizedPayload {
command := shared.GetString(state.Input, "command")
description := shared.GetString(state.Input, "description")
timeout := shared.GetInt(state.Input, "timeout")
background := shared.GetBool(state.Input, "background")
// OpenCode tool state might have the command
if command == "" {
if state, ok := args["state"].(map[string]any); ok {
command = shared.GetString(state, "command")
// Use factory function
payload := streams.NewShellExec(command, "", description, timeout, background)
// Add output if available
if state.Output != "" || state.Metadata != nil {
payload.ShellExec().Output = &streams.ShellExecOutput{
Stdout: state.Output,
}
// Extract exit code from metadata
if state.Metadata != nil {
if exitCode, ok := state.Metadata["exit"].(float64); ok {
payload.ShellExec().Output.ExitCode = int(exitCode)
}
}
}
return &streams.NormalizedPayload{
Kind: streams.ToolKindShellExec,
ShellExec: &streams.ShellExecPayload{
Command: command,
},
}
return payload
}
// normalizeEdit converts OpenCode edit tool data.
func (n *Normalizer) normalizeEdit(args map[string]any) *streams.NormalizedPayload {
func (n *Normalizer) normalizeEdit(state *ToolState) *streams.NormalizedPayload {
// OpenCode edit args might be in "input" or directly in args
input := args
if inputMap, ok := args["input"].(map[string]any); ok {
input := state.Input
if inputMap, ok := state.Input["input"].(map[string]any); ok {
input = inputMap
}
@@ -94,54 +129,179 @@ func (n *Normalizer) normalizeEdit(args map[string]any) *streams.NormalizedPaylo
filePath = shared.GetString(input, "file_path")
}
payload := &streams.ModifyFilePayload{
FilePath: filePath,
Mutations: []streams.FileMutation{},
}
// OpenCode might have diff or content
// Build mutations
var mutations []streams.FileMutation
if diff, ok := input["diff"].(string); ok && diff != "" {
payload.Mutations = append(payload.Mutations, streams.FileMutation{
mutations = append(mutations, streams.FileMutation{
Type: streams.MutationPatch,
Diff: diff,
})
} else {
payload.Mutations = append(payload.Mutations, streams.FileMutation{
mutations = append(mutations, streams.FileMutation{
Type: streams.MutationPatch,
})
}
return &streams.NormalizedPayload{
Kind: streams.ToolKindModifyFile,
ModifyFile: payload,
}
// Use factory function
return streams.NewModifyFile(filePath, mutations)
}
// normalizeWebFetch converts OpenCode webfetch tool data.
func (n *Normalizer) normalizeWebFetch(args map[string]any) *streams.NormalizedPayload {
url := shared.GetString(args, "url")
func (n *Normalizer) normalizeWebFetch(state *ToolState) *streams.NormalizedPayload {
url := shared.GetString(state.Input, "url")
return &streams.NormalizedPayload{
Kind: streams.ToolKindHttpRequest,
HttpRequest: &streams.HttpRequestPayload{
URL: url,
Method: "GET",
},
// Use factory function
payload := streams.NewHttpRequest(url, "GET")
// Add response if available
if state.Output != "" {
payload.HttpRequest().Response = state.Output
}
return payload
}
// normalizeGlob converts OpenCode glob tool data to code_search.
func (n *Normalizer) normalizeGlob(state *ToolState) *streams.NormalizedPayload {
pattern := shared.GetString(state.Input, "pattern")
path := shared.GetString(state.Input, "path")
// Use factory function: NewCodeSearch(query, pattern, path, glob)
// For glob, pattern goes to both pattern and glob fields
payload := streams.NewCodeSearch("", pattern, path, pattern)
// Parse output (newline-separated file list) and metadata
if state.Output != "" || state.Metadata != nil {
payload.CodeSearch().Output = &streams.CodeSearchOutput{}
// Parse file list from output
if state.Output != "" {
lines := strings.Split(strings.TrimSpace(state.Output), "\n")
// Filter out empty lines and the truncation message
var files []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "(Results are truncated") {
files = append(files, line)
}
}
payload.CodeSearch().Output.Files = files
}
// Extract metadata
if state.Metadata != nil {
if count, ok := state.Metadata["count"].(float64); ok {
payload.CodeSearch().Output.FileCount = int(count)
}
if truncated, ok := state.Metadata["truncated"].(bool); ok {
payload.CodeSearch().Output.Truncated = truncated
}
}
}
return payload
}
// normalizeGrep converts OpenCode grep tool data to code_search.
func (n *Normalizer) normalizeGrep(state *ToolState) *streams.NormalizedPayload {
pattern := shared.GetString(state.Input, "pattern")
path := shared.GetString(state.Input, "path")
query := shared.GetString(state.Input, "query")
// Use factory function: NewCodeSearch(query, pattern, path, glob)
payload := streams.NewCodeSearch(query, pattern, path, "")
// Parse output and metadata
if state.Output != "" || state.Metadata != nil {
payload.CodeSearch().Output = &streams.CodeSearchOutput{}
// Parse file list from output (grep typically outputs file:line format)
if state.Output != "" {
lines := strings.Split(strings.TrimSpace(state.Output), "\n")
fileSet := make(map[string]bool)
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Extract file path (before first colon for grep output)
if idx := strings.Index(line, ":"); idx > 0 {
fileSet[line[:idx]] = true
} else {
fileSet[line] = true
}
}
var files []string
for f := range fileSet {
files = append(files, f)
}
payload.CodeSearch().Output.Files = files
payload.CodeSearch().Output.FileCount = len(files)
}
// Extract metadata
if state.Metadata != nil {
if truncated, ok := state.Metadata["truncated"].(bool); ok {
payload.CodeSearch().Output.Truncated = truncated
}
}
}
return payload
}
// normalizeRead converts OpenCode read tool data.
func (n *Normalizer) normalizeRead(state *ToolState) *streams.NormalizedPayload {
filePath := shared.GetString(state.Input, "path")
if filePath == "" {
filePath = shared.GetString(state.Input, "file_path")
}
offset := shared.GetInt(state.Input, "offset")
limit := shared.GetInt(state.Input, "limit")
// Use factory function
payload := streams.NewReadFile(filePath, offset, limit)
// Add output if available
if state.Output != "" || state.Metadata != nil {
payload.ReadFile().Output = &streams.ReadFileOutput{
Content: state.Output,
}
if state.Metadata != nil {
if lineCount, ok := state.Metadata["line_count"].(float64); ok {
payload.ReadFile().Output.LineCount = int(lineCount)
}
if truncated, ok := state.Metadata["truncated"].(bool); ok {
payload.ReadFile().Output.Truncated = truncated
}
}
// Calculate line count from content if not in metadata
if payload.ReadFile().Output.LineCount == 0 && state.Output != "" {
payload.ReadFile().Output.LineCount = strings.Count(state.Output, "\n") + 1
}
}
return payload
}
// normalizeGeneric wraps unknown tools as generic.
func (n *Normalizer) normalizeGeneric(toolName string, args map[string]any) *streams.NormalizedPayload {
return &streams.NormalizedPayload{
Kind: streams.ToolKindGeneric,
Generic: &streams.GenericPayload{
Name: toolName,
Input: args,
},
func (n *Normalizer) normalizeGeneric(toolName string, state *ToolState) *streams.NormalizedPayload {
// Use factory function
payload := streams.NewGeneric(toolName, state.Input)
// Add output if available
if state.Output != "" {
payload.Generic().Output = state.Output
}
return payload
}
// normalizeBashResult updates bash payload with result data.
// Deprecated: Use ToolState in NormalizeToolCall instead
func (n *Normalizer) normalizeBashResult(payload *streams.ShellExecPayload, result any) {
if payload.Output == nil {
payload.Output = &streams.ShellExecOutput{}
@@ -159,4 +319,3 @@ func (n *Normalizer) normalizeBashResult(payload *streams.ShellExecPayload, resu
}
}
}
@@ -0,0 +1,496 @@
package opencode
import (
"testing"
"github.com/kandev/kandev/internal/agentctl/types/streams"
)
// TestNormalizerBash tests the normalizer's bash handling.
func TestNormalizerBash(t *testing.T) {
normalizer := NewNormalizer()
t.Run("extracts command, description, timeout, background", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"command": "ls -la",
"description": "List files",
"timeout": float64(30000),
"background": true,
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolBash, state)
if result.Kind() != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, result.Kind())
}
if result.ShellExec() == nil {
t.Fatal("expected ShellExec to be set")
}
if result.ShellExec().Command != "ls -la" {
t.Errorf("expected Command 'ls -la', got %q", result.ShellExec().Command)
}
if result.ShellExec().Description != "List files" {
t.Errorf("expected Description 'List files', got %q", result.ShellExec().Description)
}
if result.ShellExec().Timeout != 30000 {
t.Errorf("expected Timeout 30000, got %d", result.ShellExec().Timeout)
}
if !result.ShellExec().Background {
t.Error("expected Background to be true")
}
})
t.Run("includes output with exit code from metadata", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"command": "echo hello",
},
Output: "hello",
Metadata: map[string]any{
"exit": float64(0),
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolBash, state)
if result.ShellExec().Output == nil {
t.Fatal("expected Output to be set")
}
if result.ShellExec().Output.Stdout != "hello" {
t.Errorf("expected Stdout 'hello', got %q", result.ShellExec().Output.Stdout)
}
if result.ShellExec().Output.ExitCode != 0 {
t.Errorf("expected ExitCode 0, got %d", result.ShellExec().Output.ExitCode)
}
})
t.Run("handles nil state gracefully", func(t *testing.T) {
result := normalizer.NormalizeToolCall(OpenCodeToolBash, nil)
if result.Kind() != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, result.Kind())
}
})
}
// TestNormalizerEdit tests the normalizer's edit handling.
func TestNormalizerEdit(t *testing.T) {
normalizer := NewNormalizer()
t.Run("extracts path from input directly", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"path": "/workspace/file.ts",
"diff": "@@ -1,1 +1,1 @@\n-old\n+new\n",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolEdit, state)
if result.Kind() != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind())
}
if result.ModifyFile() == nil {
t.Fatal("expected ModifyFile to be set")
}
if result.ModifyFile().FilePath != "/workspace/file.ts" {
t.Errorf("expected FilePath '/workspace/file.ts', got %q", result.ModifyFile().FilePath)
}
if len(result.ModifyFile().Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile().Mutations))
}
if result.ModifyFile().Mutations[0].Diff != "@@ -1,1 +1,1 @@\n-old\n+new\n" {
t.Error("expected diff to be preserved")
}
})
t.Run("extracts path from nested input map", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"input": map[string]any{
"path": "/workspace/nested.ts",
},
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolEdit, state)
if result.ModifyFile().FilePath != "/workspace/nested.ts" {
t.Errorf("expected FilePath '/workspace/nested.ts', got %q", result.ModifyFile().FilePath)
}
})
t.Run("falls back to file_path key", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"file_path": "/workspace/fallback.ts",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolEdit, state)
if result.ModifyFile().FilePath != "/workspace/fallback.ts" {
t.Errorf("expected FilePath '/workspace/fallback.ts', got %q", result.ModifyFile().FilePath)
}
})
t.Run("creates empty mutation when no diff", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"path": "/workspace/file.ts",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolEdit, state)
if len(result.ModifyFile().Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile().Mutations))
}
if result.ModifyFile().Mutations[0].Type != streams.MutationPatch {
t.Errorf("expected MutationType %q, got %q", streams.MutationPatch, result.ModifyFile().Mutations[0].Type)
}
})
}
// TestNormalizerWebFetch tests the normalizer's webfetch handling.
func TestNormalizerWebFetch(t *testing.T) {
normalizer := NewNormalizer()
t.Run("extracts URL and uses GET method", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"url": "https://example.com/api",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolWebFetch, state)
if result.Kind() != streams.ToolKindHttpRequest {
t.Errorf("expected Kind %q, got %q", streams.ToolKindHttpRequest, result.Kind())
}
if result.HttpRequest() == nil {
t.Fatal("expected HttpRequest to be set")
}
if result.HttpRequest().URL != "https://example.com/api" {
t.Errorf("expected URL 'https://example.com/api', got %q", result.HttpRequest().URL)
}
if result.HttpRequest().Method != "GET" {
t.Errorf("expected Method 'GET', got %q", result.HttpRequest().Method)
}
})
t.Run("includes response when output available", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"url": "https://example.com",
},
Output: "Response body content",
}
result := normalizer.NormalizeToolCall(OpenCodeToolWebFetch, state)
if result.HttpRequest().Response != "Response body content" {
t.Errorf("expected Response 'Response body content', got %q", result.HttpRequest().Response)
}
})
}
// TestNormalizerGlob tests the normalizer's glob handling.
func TestNormalizerGlob(t *testing.T) {
normalizer := NewNormalizer()
t.Run("extracts pattern and path", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "**/*.ts",
"path": "/workspace",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolGlob, state)
if result.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind())
}
if result.CodeSearch() == nil {
t.Fatal("expected CodeSearch to be set")
}
if result.CodeSearch().Glob != "**/*.ts" {
t.Errorf("expected Glob '**/*.ts', got %q", result.CodeSearch().Glob)
}
if result.CodeSearch().Path != "/workspace" {
t.Errorf("expected Path '/workspace', got %q", result.CodeSearch().Path)
}
})
t.Run("parses file list from output", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "**/*.ts",
},
Output: "file1.ts\nfile2.ts\nsrc/file3.ts",
}
result := normalizer.NormalizeToolCall(OpenCodeToolGlob, state)
if result.CodeSearch().Output == nil {
t.Fatal("expected Output to be set")
}
if len(result.CodeSearch().Output.Files) != 3 {
t.Errorf("expected 3 files, got %d", len(result.CodeSearch().Output.Files))
}
})
t.Run("filters out truncation message from output", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "**/*",
},
Output: "file1.ts\n(Results are truncated...)",
}
result := normalizer.NormalizeToolCall(OpenCodeToolGlob, state)
if len(result.CodeSearch().Output.Files) != 1 {
t.Errorf("expected 1 file (truncation msg filtered), got %d", len(result.CodeSearch().Output.Files))
}
})
t.Run("extracts count and truncated from metadata", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "**/*",
},
Output: "file1.ts",
Metadata: map[string]any{
"count": float64(100),
"truncated": true,
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolGlob, state)
if result.CodeSearch().Output.FileCount != 100 {
t.Errorf("expected FileCount 100, got %d", result.CodeSearch().Output.FileCount)
}
if !result.CodeSearch().Output.Truncated {
t.Error("expected Truncated to be true")
}
})
}
// TestNormalizerGrep tests the normalizer's grep handling.
func TestNormalizerGrep(t *testing.T) {
normalizer := NewNormalizer()
t.Run("extracts pattern, path, and query", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "func.*Error",
"path": "/workspace",
"query": "error handling",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolGrep, state)
if result.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind())
}
if result.CodeSearch() == nil {
t.Fatal("expected CodeSearch to be set")
}
if result.CodeSearch().Pattern != "func.*Error" {
t.Errorf("expected Pattern 'func.*Error', got %q", result.CodeSearch().Pattern)
}
if result.CodeSearch().Query != "error handling" {
t.Errorf("expected Query 'error handling', got %q", result.CodeSearch().Query)
}
})
t.Run("parses grep output with file:line format", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "func",
},
Output: "file1.go:10:func main()\nfile1.go:20:func helper()\nfile2.go:5:func test()",
}
result := normalizer.NormalizeToolCall(OpenCodeToolGrep, state)
if result.CodeSearch().Output == nil {
t.Fatal("expected Output to be set")
}
// Should deduplicate files
if result.CodeSearch().Output.FileCount != 2 {
t.Errorf("expected FileCount 2 (deduplicated), got %d", result.CodeSearch().Output.FileCount)
}
})
t.Run("handles files-only output", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"pattern": "test",
},
Output: "file1.go\nfile2.go\nfile3.go",
}
result := normalizer.NormalizeToolCall(OpenCodeToolGrep, state)
if len(result.CodeSearch().Output.Files) != 3 {
t.Errorf("expected 3 files, got %d", len(result.CodeSearch().Output.Files))
}
})
}
// TestNormalizerRead tests the normalizer's read handling.
func TestNormalizerRead(t *testing.T) {
normalizer := NewNormalizer()
t.Run("extracts path, offset, limit", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"path": "/workspace/config.json",
"offset": float64(10),
"limit": float64(50),
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolRead, state)
if result.Kind() != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, result.Kind())
}
if result.ReadFile() == nil {
t.Fatal("expected ReadFile to be set")
}
if result.ReadFile().FilePath != "/workspace/config.json" {
t.Errorf("expected FilePath '/workspace/config.json', got %q", result.ReadFile().FilePath)
}
if result.ReadFile().Offset != 10 {
t.Errorf("expected Offset 10, got %d", result.ReadFile().Offset)
}
if result.ReadFile().Limit != 50 {
t.Errorf("expected Limit 50, got %d", result.ReadFile().Limit)
}
})
t.Run("falls back to file_path key", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"file_path": "/workspace/fallback.json",
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolRead, state)
if result.ReadFile().FilePath != "/workspace/fallback.json" {
t.Errorf("expected FilePath '/workspace/fallback.json', got %q", result.ReadFile().FilePath)
}
})
t.Run("includes output with content and line count", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"path": "/workspace/file.txt",
},
Output: "line1\nline2\nline3",
}
result := normalizer.NormalizeToolCall(OpenCodeToolRead, state)
if result.ReadFile().Output == nil {
t.Fatal("expected Output to be set")
}
if result.ReadFile().Output.Content != "line1\nline2\nline3" {
t.Errorf("expected Content, got %q", result.ReadFile().Output.Content)
}
// Line count should be calculated from content
if result.ReadFile().Output.LineCount != 3 {
t.Errorf("expected LineCount 3, got %d", result.ReadFile().Output.LineCount)
}
})
t.Run("extracts line_count and truncated from metadata", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"path": "/workspace/large.txt",
},
Output: "content here",
Metadata: map[string]any{
"line_count": float64(1000),
"truncated": true,
},
}
result := normalizer.NormalizeToolCall(OpenCodeToolRead, state)
if result.ReadFile().Output.LineCount != 1000 {
t.Errorf("expected LineCount 1000, got %d", result.ReadFile().Output.LineCount)
}
if !result.ReadFile().Output.Truncated {
t.Error("expected Truncated to be true")
}
})
}
// TestNormalizerGeneric tests the normalizer's generic handling.
func TestNormalizerGeneric(t *testing.T) {
normalizer := NewNormalizer()
t.Run("wraps unknown tools as generic", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{
"custom_field": "custom_value",
},
}
result := normalizer.NormalizeToolCall("custom_tool", state)
if result.Kind() != streams.ToolKindGeneric {
t.Errorf("expected Kind %q, got %q", streams.ToolKindGeneric, result.Kind())
}
if result.Generic() == nil {
t.Fatal("expected Generic to be set")
}
if result.Generic().Name != "custom_tool" {
t.Errorf("expected Name 'custom_tool', got %q", result.Generic().Name)
}
})
t.Run("includes output when available", func(t *testing.T) {
state := &ToolState{
Input: map[string]any{},
Output: "tool output",
}
result := normalizer.NormalizeToolCall("unknown", state)
if result.Generic().Output != "tool output" {
t.Errorf("expected Output 'tool output', got %v", result.Generic().Output)
}
})
}
// TestNormalizeToolResult tests the deprecated result handler.
func TestNormalizeToolResult(t *testing.T) {
normalizer := NewNormalizer()
t.Run("updates shell exec output from string", func(t *testing.T) {
payload := streams.NewShellExec("ls", "", "", 0, false)
normalizer.NormalizeToolResult(payload, "file1\nfile2")
if payload.ShellExec().Output == nil {
t.Fatal("expected Output to be set")
}
if payload.ShellExec().Output.Stdout != "file1\nfile2" {
t.Errorf("expected Stdout, got %q", payload.ShellExec().Output.Stdout)
}
})
t.Run("updates shell exec output from map", func(t *testing.T) {
payload := streams.NewShellExec("cmd", "", "", 0, false)
normalizer.NormalizeToolResult(payload, map[string]any{
"output": "stdout content",
"error": "stderr content",
})
if payload.ShellExec().Output.Stdout != "stdout content" {
t.Errorf("expected Stdout 'stdout content', got %q", payload.ShellExec().Output.Stdout)
}
if payload.ShellExec().Output.Stderr != "stderr content" {
t.Errorf("expected Stderr 'stderr content', got %q", payload.ShellExec().Output.Stderr)
}
})
t.Run("updates http request response", func(t *testing.T) {
payload := streams.NewHttpRequest("https://example.com", "GET")
normalizer.NormalizeToolResult(payload, "response body")
if payload.HttpRequest().Response != "response body" {
t.Errorf("expected Response 'response body', got %q", payload.HttpRequest().Response)
}
})
t.Run("updates generic output", func(t *testing.T) {
payload := streams.NewGeneric("tool", nil)
normalizer.NormalizeToolResult(payload, map[string]any{"data": "value"})
if payload.Generic().Output == nil {
t.Fatal("expected Output to be set")
}
})
t.Run("does not overwrite existing output", func(t *testing.T) {
payload := streams.NewShellExec("ls", "", "", 0, false)
payload.ShellExec().Output = &streams.ShellExecOutput{Stdout: "existing"}
normalizer.NormalizeToolResult(payload, "new output")
// Should not overwrite
if payload.ShellExec().Output.Stdout != "existing" {
t.Errorf("expected Stdout to remain 'existing', got %q", payload.ShellExec().Output.Stdout)
}
})
}
// TestNewNormalizer tests the constructor.
func TestNewNormalizer(t *testing.T) {
normalizer := NewNormalizer()
if normalizer == nil {
t.Fatal("expected non-nil normalizer")
}
}
@@ -24,6 +24,10 @@ var debugLogDir = resolveDebugLogDir()
// debugLogMu protects concurrent writes to debug log files.
var debugLogMu sync.Mutex
// initializedFiles tracks which log files have been truncated in this session.
// First write to a file truncates it; subsequent writes append.
var initializedFiles = make(map[string]bool)
// Protocol constants for debug file naming
const (
ProtocolACP = "acp"
@@ -78,6 +82,7 @@ func LogNormalizedEvent(protocol, agentID string, event *streams.AgentEvent) {
}
// writeJSONLine writes a JSON entry as a line to the specified file.
// On first write to a file in this session, the file is truncated.
func writeJSONLine(logFile string, entry any) {
entryJSON, err := json.Marshal(entry)
if err != nil {
@@ -88,7 +93,16 @@ func writeJSONLine(logFile string, entry any) {
debugLogMu.Lock()
defer debugLogMu.Unlock()
f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
// Determine open flags: truncate on first write, append on subsequent
flags := os.O_CREATE | os.O_WRONLY
if initializedFiles[logFile] {
flags |= os.O_APPEND
} else {
flags |= os.O_TRUNC
initializedFiles[logFile] = true
}
f, err := os.OpenFile(logFile, flags, 0644)
if err != nil {
log.Printf("[DEBUG] Failed to open log file %s: %v", logFile, err)
return
@@ -75,6 +75,72 @@ func NormalizeShellResult(payload *streams.ShellExecPayload, result any) {
}
}
// MaxContentLength is the maximum length for tool output content before truncation.
const MaxContentLength = 50000
// MaxFileCount is the maximum number of files to include in code search results.
const MaxFileCount = 500
// TruncateIfNeeded truncates a string if it exceeds maxLen.
func TruncateIfNeeded(s string, maxLen int) (string, bool) {
if len(s) <= maxLen {
return s, false
}
return s[:maxLen], true
}
// NormalizeReadResult populates ReadFilePayload.Output with result content.
func NormalizeReadResult(payload *streams.ReadFilePayload, result string) {
lines := SplitLines(result)
content, truncated := TruncateIfNeeded(result, MaxContentLength)
payload.Output = &streams.ReadFileOutput{
Content: content,
LineCount: len(lines),
Truncated: truncated,
Language: DetectLanguage(payload.FilePath),
}
}
// NormalizeCodeSearchResult populates CodeSearchPayload.Output with result content.
func NormalizeCodeSearchResult(payload *streams.CodeSearchPayload, result string) {
result = strings.TrimSpace(result)
if result == "" {
payload.Output = &streams.CodeSearchOutput{
Files: []string{},
FileCount: 0,
}
return
}
files := strings.Split(result, "\n")
truncated := false
if len(files) > MaxFileCount {
files = files[:MaxFileCount]
truncated = true
}
payload.Output = &streams.CodeSearchOutput{
Files: files,
FileCount: len(files),
Truncated: truncated,
}
}
// NormalizeModifyResult updates ModifyFilePayload with result content for Write operations.
func NormalizeModifyResult(payload *streams.ModifyFilePayload, result string) {
// For Write tool, store the written content confirmation
// The tool result confirms what was written
if len(payload.Mutations) > 0 {
mut := &payload.Mutations[0]
// If Content not already set from input args (for create), use result
if mut.Content == "" && mut.NewContent == "" && result != "" {
content, _ := TruncateIfNeeded(result, MaxContentLength)
mut.Content = content
}
}
}
// DetectLanguage maps file extension to language identifier.
// Used for syntax highlighting in diffs.
func DetectLanguage(path string) string {
@@ -67,7 +67,8 @@ type Adapter struct {
sessionStatusSent bool // Whether we've sent the session status event
// Track pending tool calls to auto-complete on result
pendingToolCalls map[string]bool
// Maps tool_use_id to the NormalizedPayload for enrichment with results
pendingToolCalls map[string]*streams.NormalizedPayload
// Agent info
agentInfo *AgentInfo
@@ -117,7 +118,7 @@ func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter {
cancel: cancel,
updatesCh: make(chan AgentEvent, 100),
mainModelContextWindow: defaultContextWindow,
pendingToolCalls: make(map[string]bool),
pendingToolCalls: make(map[string]*streams.NormalizedPayload),
}
}
@@ -534,6 +535,9 @@ func (a *Adapter) handleMessage(msg *claudecode.CLIMessage) {
case claudecode.MessageTypeAssistant:
a.handleAssistantMessage(msg, sessionID, operationID)
case claudecode.MessageTypeUser:
a.handleUserMessage(msg, sessionID, operationID)
case claudecode.MessageTypeResult:
a.handleResultMessage(msg, sessionID, operationID)
@@ -583,6 +587,9 @@ func (a *Adapter) handleAssistantMessage(msg *claudecode.CLIMessage, sessionID,
return
}
// Extract parent tool use ID for subagent nesting
parentToolUseID := msg.ParentToolUseID
// Log content block types for debugging
blockTypes := make([]string, 0, len(msg.Message.Content))
for _, block := range msg.Message.Content {
@@ -590,7 +597,8 @@ func (a *Adapter) handleAssistantMessage(msg *claudecode.CLIMessage, sessionID,
}
a.logger.Info("processing assistant message",
zap.Int("num_blocks", len(msg.Message.Content)),
zap.Strings("block_types", blockTypes))
zap.Strings("block_types", blockTypes),
zap.String("parent_tool_use_id", parentToolUseID))
// Update agent version and track main model name from model info
if msg.Message.Model != "" && a.agentInfo != nil {
@@ -649,9 +657,9 @@ func (a *Adapter) handleAssistantMessage(msg *claudecode.CLIMessage, sessionID,
zap.String("tool_type", toolType),
zap.String("title", toolTitle))
// Track this tool call as pending
// Track this tool call as pending with its payload for result enrichment
a.mu.Lock()
a.pendingToolCalls[block.ID] = true
a.pendingToolCalls[block.ID] = normalizedPayload
a.mu.Unlock()
a.sendUpdate(AgentEvent{
@@ -659,33 +667,13 @@ func (a *Adapter) handleAssistantMessage(msg *claudecode.CLIMessage, sessionID,
SessionID: sessionID,
OperationID: operationID,
ToolCallID: block.ID,
ParentToolCallID: parentToolUseID,
ToolName: block.Name,
ToolTitle: toolTitle,
ToolStatus: "running",
NormalizedPayload: normalizedPayload,
})
case "tool_result":
status := "complete"
if block.IsError {
status = "error"
}
a.logger.Info("tool_result block received",
zap.String("tool_call_id", block.ToolUseID),
zap.String("status", status))
// Remove from pending
a.mu.Lock()
delete(a.pendingToolCalls, block.ToolUseID)
a.mu.Unlock()
a.sendUpdate(AgentEvent{
Type: streams.EventTypeToolUpdate,
SessionID: sessionID,
OperationID: operationID,
ToolCallID: block.ToolUseID,
ToolStatus: status,
})
}
}
@@ -720,6 +708,47 @@ func (a *Adapter) handleAssistantMessage(msg *claudecode.CLIMessage, sessionID,
}
}
// handleUserMessage processes user messages containing tool results.
// Claude Code sends tool results back as user messages with tool_result content blocks.
func (a *Adapter) handleUserMessage(msg *claudecode.CLIMessage, sessionID, operationID string) {
if msg.Message == nil {
return
}
// Process content blocks looking for tool_result
for _, block := range msg.Message.Content {
if block.Type != "tool_result" {
continue
}
// Get and enrich the pending payload with result content
a.mu.Lock()
payload := a.pendingToolCalls[block.ToolUseID]
delete(a.pendingToolCalls, block.ToolUseID)
a.mu.Unlock()
// Enrich payload with result content
if payload != nil && block.Content != "" {
a.normalizer.NormalizeToolResult(payload, block.Content)
}
// Determine status
status := "complete"
if block.IsError {
status = "error"
}
a.sendUpdate(AgentEvent{
Type: streams.EventTypeToolUpdate,
SessionID: sessionID,
OperationID: operationID,
ToolCallID: block.ToolUseID,
ToolStatus: status,
NormalizedPayload: payload,
})
}
}
// handleResultMessage processes result (completion) messages.
func (a *Adapter) handleResultMessage(msg *claudecode.CLIMessage, sessionID, operationID string) {
a.logger.Info("received result message",
@@ -741,7 +770,7 @@ func (a *Adapter) handleResultMessage(msg *claudecode.CLIMessage, sessionID, ope
for toolID := range a.pendingToolCalls {
pendingTools = append(pendingTools, toolID)
}
a.pendingToolCalls = make(map[string]bool) // Clear pending
a.pendingToolCalls = make(map[string]*streams.NormalizedPayload) // Clear pending
a.mu.Unlock()
for _, toolID := range pendingTools {
@@ -57,20 +57,34 @@ func (n *Normalizer) NormalizeToolCall(toolName string, args map[string]any) *st
// NormalizeToolResult updates the payload with tool result data.
func (n *Normalizer) NormalizeToolResult(payload *streams.NormalizedPayload, result any) {
switch payload.Kind {
resultStr, _ := result.(string)
switch payload.Kind() {
case streams.ToolKindReadFile:
if payload.ReadFile() != nil && resultStr != "" {
shared.NormalizeReadResult(payload.ReadFile(), resultStr)
}
case streams.ToolKindCodeSearch:
if payload.CodeSearch() != nil && resultStr != "" {
shared.NormalizeCodeSearchResult(payload.CodeSearch(), resultStr)
}
case streams.ToolKindModifyFile:
if payload.ModifyFile() != nil && resultStr != "" {
shared.NormalizeModifyResult(payload.ModifyFile(), resultStr)
}
case streams.ToolKindShellExec:
if payload.ShellExec != nil {
shared.NormalizeShellResult(payload.ShellExec, result)
if payload.ShellExec() != nil {
shared.NormalizeShellResult(payload.ShellExec(), result)
}
case streams.ToolKindHttpRequest:
if payload.HttpRequest != nil {
if payload.HttpRequest() != nil {
if r, ok := result.(string); ok {
payload.HttpRequest.Response = r
payload.HttpRequest().Response = r
}
}
case streams.ToolKindGeneric:
if payload.Generic != nil {
payload.Generic.Output = result
if payload.Generic() != nil {
payload.Generic().Output = result
}
}
}
@@ -82,14 +96,11 @@ func (n *Normalizer) normalizeEdit(toolName string, args map[string]any) *stream
newString := shared.GetString(args, "new_string")
content := shared.GetString(args, "content")
payload := &streams.ModifyFilePayload{
FilePath: filePath,
Mutations: []streams.FileMutation{},
}
var mutations []streams.FileMutation
if toolName == claudecode.ToolWrite {
// Write is a full file creation/replacement
payload.Mutations = append(payload.Mutations, streams.FileMutation{
mutations = append(mutations, streams.FileMutation{
Type: streams.MutationCreate,
Content: content,
})
@@ -106,13 +117,11 @@ func (n *Normalizer) normalizeEdit(toolName string, args map[string]any) *stream
mutation.Diff = shared.GenerateUnifiedDiff(oldString, newString, filePath, 0)
}
payload.Mutations = append(payload.Mutations, mutation)
mutations = append(mutations, mutation)
}
return &streams.NormalizedPayload{
Kind: streams.ToolKindModifyFile,
ModifyFile: payload,
}
// Use factory function
return streams.NewModifyFile(filePath, mutations)
}
// normalizeRead converts stream-json Read tool data.
@@ -192,15 +201,12 @@ func (n *Normalizer) normalizeManageTodos(toolName string, args map[string]any)
operation = "write"
}
payload := &streams.ManageTodosPayload{
Operation: operation,
}
// Extract items if present
if items, ok := args["items"].([]any); ok {
for _, item := range items {
var items []streams.TodoItem
if rawItems, ok := args["items"].([]any); ok {
for _, item := range rawItems {
if itemMap, ok := item.(map[string]any); ok {
payload.Items = append(payload.Items, streams.TodoItem{
items = append(items, streams.TodoItem{
ID: shared.GetString(itemMap, "id"),
Description: shared.GetString(itemMap, "description"),
Status: shared.GetString(itemMap, "status"),
@@ -209,10 +215,8 @@ func (n *Normalizer) normalizeManageTodos(toolName string, args map[string]any)
}
}
return &streams.NormalizedPayload{
Kind: streams.ToolKindManageTodos,
ManageTodos: payload,
}
// Use factory function
return streams.NewManageTodos(operation, items)
}
// normalizeGeneric wraps unknown tools as generic.
@@ -33,16 +33,16 @@ func TestStreamJSONNormalization(t *testing.T) {
// Verify the Kind is set correctly based on tool type
switch toolType {
case "tool_edit":
if payload.Kind != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, payload.Kind)
if payload.Kind() != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, payload.Kind())
}
case "tool_read":
if payload.Kind != streams.ToolKindReadFile && payload.Kind != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q or %q, got %q", streams.ToolKindReadFile, streams.ToolKindCodeSearch, payload.Kind)
if payload.Kind() != streams.ToolKindReadFile && payload.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q or %q, got %q", streams.ToolKindReadFile, streams.ToolKindCodeSearch, payload.Kind())
}
case "tool_execute":
if payload.Kind != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, payload.Kind)
if payload.Kind() != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, payload.Kind())
}
}
})
@@ -183,19 +183,19 @@ func TestNormalizerEdit(t *testing.T) {
"new_string": "const x = 2;",
}
result := normalizer.NormalizeToolCall(claudecode.ToolEdit, args)
if result.Kind != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind)
if result.Kind() != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind())
}
if result.ModifyFile == nil {
if result.ModifyFile() == nil {
t.Fatal("expected ModifyFile to be set")
}
if result.ModifyFile.FilePath != "/workspace/app.ts" {
t.Errorf("expected FilePath '/workspace/app.ts', got %q", result.ModifyFile.FilePath)
if result.ModifyFile().FilePath != "/workspace/app.ts" {
t.Errorf("expected FilePath '/workspace/app.ts', got %q", result.ModifyFile().FilePath)
}
if len(result.ModifyFile.Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile.Mutations))
if len(result.ModifyFile().Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile().Mutations))
}
mutation := result.ModifyFile.Mutations[0]
mutation := result.ModifyFile().Mutations[0]
if mutation.OldContent != "const x = 1;" {
t.Errorf("expected OldContent 'const x = 1;', got %q", mutation.OldContent)
}
@@ -211,10 +211,10 @@ func TestNormalizerEdit(t *testing.T) {
"new_string": "const x = 2;",
}
result := normalizer.NormalizeToolCall(claudecode.ToolEdit, args)
if result.ModifyFile == nil || len(result.ModifyFile.Mutations) == 0 {
if result.ModifyFile() == nil || len(result.ModifyFile().Mutations) == 0 {
t.Fatal("expected mutation")
}
if result.ModifyFile.Mutations[0].Diff == "" {
if result.ModifyFile().Mutations[0].Diff == "" {
t.Error("expected diff to be generated")
}
})
@@ -226,10 +226,10 @@ func TestNormalizerEdit(t *testing.T) {
"new_string": "new content",
}
result := normalizer.NormalizeToolCall(claudecode.ToolEdit, args)
if result.ModifyFile == nil || len(result.ModifyFile.Mutations) == 0 {
if result.ModifyFile() == nil || len(result.ModifyFile().Mutations) == 0 {
t.Fatal("expected mutation")
}
if result.ModifyFile.Mutations[0].Diff != "" {
if result.ModifyFile().Mutations[0].Diff != "" {
t.Error("expected no diff when old_string is empty")
}
})
@@ -240,19 +240,19 @@ func TestNormalizerEdit(t *testing.T) {
"content": "# Contributing\n\nThank you for your interest!",
}
result := normalizer.NormalizeToolCall(claudecode.ToolWrite, args)
if result.Kind != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind)
if result.Kind() != streams.ToolKindModifyFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindModifyFile, result.Kind())
}
if result.ModifyFile == nil {
if result.ModifyFile() == nil {
t.Fatal("expected ModifyFile to be set")
}
if result.ModifyFile.FilePath != "/workspace/CONTRIBUTING.md" {
t.Errorf("expected FilePath '/workspace/CONTRIBUTING.md', got %q", result.ModifyFile.FilePath)
if result.ModifyFile().FilePath != "/workspace/CONTRIBUTING.md" {
t.Errorf("expected FilePath '/workspace/CONTRIBUTING.md', got %q", result.ModifyFile().FilePath)
}
if len(result.ModifyFile.Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile.Mutations))
if len(result.ModifyFile().Mutations) != 1 {
t.Fatalf("expected 1 mutation, got %d", len(result.ModifyFile().Mutations))
}
mutation := result.ModifyFile.Mutations[0]
mutation := result.ModifyFile().Mutations[0]
if mutation.Type != streams.MutationCreate {
t.Errorf("expected MutationType %q, got %q", streams.MutationCreate, mutation.Type)
}
@@ -273,20 +273,20 @@ func TestNormalizerRead(t *testing.T) {
"limit": float64(50),
}
result := normalizer.NormalizeToolCall(claudecode.ToolRead, args)
if result.Kind != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, result.Kind)
if result.Kind() != streams.ToolKindReadFile {
t.Errorf("expected Kind %q, got %q", streams.ToolKindReadFile, result.Kind())
}
if result.ReadFile == nil {
if result.ReadFile() == nil {
t.Fatal("expected ReadFile to be set")
}
if result.ReadFile.FilePath != "/workspace/config.json" {
t.Errorf("expected FilePath '/workspace/config.json', got %q", result.ReadFile.FilePath)
if result.ReadFile().FilePath != "/workspace/config.json" {
t.Errorf("expected FilePath '/workspace/config.json', got %q", result.ReadFile().FilePath)
}
if result.ReadFile.Offset != 10 {
t.Errorf("expected Offset 10, got %d", result.ReadFile.Offset)
if result.ReadFile().Offset != 10 {
t.Errorf("expected Offset 10, got %d", result.ReadFile().Offset)
}
if result.ReadFile.Limit != 50 {
t.Errorf("expected Limit 50, got %d", result.ReadFile.Limit)
if result.ReadFile().Limit != 50 {
t.Errorf("expected Limit 50, got %d", result.ReadFile().Limit)
}
})
}
@@ -301,17 +301,17 @@ func TestNormalizerExecute(t *testing.T) {
"description": "List files",
}
result := normalizer.NormalizeToolCall(claudecode.ToolBash, args)
if result.Kind != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, result.Kind)
if result.Kind() != streams.ToolKindShellExec {
t.Errorf("expected Kind %q, got %q", streams.ToolKindShellExec, result.Kind())
}
if result.ShellExec == nil {
if result.ShellExec() == nil {
t.Fatal("expected ShellExec to be set")
}
if result.ShellExec.Command != "ls -la" {
t.Errorf("expected Command 'ls -la', got %q", result.ShellExec.Command)
if result.ShellExec().Command != "ls -la" {
t.Errorf("expected Command 'ls -la', got %q", result.ShellExec().Command)
}
if result.ShellExec.Description != "List files" {
t.Errorf("expected Description 'List files', got %q", result.ShellExec.Description)
if result.ShellExec().Description != "List files" {
t.Errorf("expected Description 'List files', got %q", result.ShellExec().Description)
}
})
@@ -321,11 +321,11 @@ func TestNormalizerExecute(t *testing.T) {
"timeout": float64(30000),
}
result := normalizer.NormalizeToolCall(claudecode.ToolBash, args)
if result.ShellExec == nil {
if result.ShellExec() == nil {
t.Fatal("expected ShellExec to be set")
}
if result.ShellExec.Timeout != 30000 {
t.Errorf("expected Timeout 30000, got %d", result.ShellExec.Timeout)
if result.ShellExec().Timeout != 30000 {
t.Errorf("expected Timeout 30000, got %d", result.ShellExec().Timeout)
}
})
@@ -335,10 +335,10 @@ func TestNormalizerExecute(t *testing.T) {
"run_in_background": true,
}
result := normalizer.NormalizeToolCall(claudecode.ToolBash, args)
if result.ShellExec == nil {
if result.ShellExec() == nil {
t.Fatal("expected ShellExec to be set")
}
if !result.ShellExec.Background {
if !result.ShellExec().Background {
t.Error("expected Background to be true")
}
})
@@ -354,17 +354,17 @@ func TestNormalizerCodeSearch(t *testing.T) {
"path": "/workspace",
}
result := normalizer.NormalizeToolCall(claudecode.ToolGlob, args)
if result.Kind != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind)
if result.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind())
}
if result.CodeSearch == nil {
if result.CodeSearch() == nil {
t.Fatal("expected CodeSearch to be set")
}
if result.CodeSearch.Glob != "**/*.ts" {
t.Errorf("expected Glob '**/*.ts', got %q", result.CodeSearch.Glob)
if result.CodeSearch().Glob != "**/*.ts" {
t.Errorf("expected Glob '**/*.ts', got %q", result.CodeSearch().Glob)
}
if result.CodeSearch.Path != "/workspace" {
t.Errorf("expected Path '/workspace', got %q", result.CodeSearch.Path)
if result.CodeSearch().Path != "/workspace" {
t.Errorf("expected Path '/workspace', got %q", result.CodeSearch().Path)
}
})
@@ -374,14 +374,14 @@ func TestNormalizerCodeSearch(t *testing.T) {
"path": "/workspace",
}
result := normalizer.NormalizeToolCall(claudecode.ToolGrep, args)
if result.Kind != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind)
if result.Kind() != streams.ToolKindCodeSearch {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCodeSearch, result.Kind())
}
if result.CodeSearch == nil {
if result.CodeSearch() == nil {
t.Fatal("expected CodeSearch to be set")
}
if result.CodeSearch.Pattern != "func.*Error" {
t.Errorf("expected Pattern 'func.*Error', got %q", result.CodeSearch.Pattern)
if result.CodeSearch().Pattern != "func.*Error" {
t.Errorf("expected Pattern 'func.*Error', got %q", result.CodeSearch().Pattern)
}
})
}
@@ -395,17 +395,17 @@ func TestNormalizerHttpRequest(t *testing.T) {
"url": "https://example.com/api",
}
result := normalizer.NormalizeToolCall(claudecode.ToolWebFetch, args)
if result.Kind != streams.ToolKindHttpRequest {
t.Errorf("expected Kind %q, got %q", streams.ToolKindHttpRequest, result.Kind)
if result.Kind() != streams.ToolKindHttpRequest {
t.Errorf("expected Kind %q, got %q", streams.ToolKindHttpRequest, result.Kind())
}
if result.HttpRequest == nil {
if result.HttpRequest() == nil {
t.Fatal("expected HttpRequest to be set")
}
if result.HttpRequest.URL != "https://example.com/api" {
t.Errorf("expected URL 'https://example.com/api', got %q", result.HttpRequest.URL)
if result.HttpRequest().URL != "https://example.com/api" {
t.Errorf("expected URL 'https://example.com/api', got %q", result.HttpRequest().URL)
}
if result.HttpRequest.Method != "GET" {
t.Errorf("expected Method 'GET', got %q", result.HttpRequest.Method)
if result.HttpRequest().Method != "GET" {
t.Errorf("expected Method 'GET', got %q", result.HttpRequest().Method)
}
})
@@ -414,17 +414,17 @@ func TestNormalizerHttpRequest(t *testing.T) {
"query": "golang testing best practices",
}
result := normalizer.NormalizeToolCall(claudecode.ToolWebSearch, args)
if result.Kind != streams.ToolKindHttpRequest {
t.Errorf("expected Kind %q, got %q", streams.ToolKindHttpRequest, result.Kind)
if result.Kind() != streams.ToolKindHttpRequest {
t.Errorf("expected Kind %q, got %q", streams.ToolKindHttpRequest, result.Kind())
}
if result.HttpRequest == nil {
if result.HttpRequest() == nil {
t.Fatal("expected HttpRequest to be set")
}
if result.HttpRequest.URL != "golang testing best practices" {
t.Errorf("expected URL 'golang testing best practices', got %q", result.HttpRequest.URL)
if result.HttpRequest().URL != "golang testing best practices" {
t.Errorf("expected URL 'golang testing best practices', got %q", result.HttpRequest().URL)
}
if result.HttpRequest.Method != "SEARCH" {
t.Errorf("expected Method 'SEARCH', got %q", result.HttpRequest.Method)
if result.HttpRequest().Method != "SEARCH" {
t.Errorf("expected Method 'SEARCH', got %q", result.HttpRequest().Method)
}
})
}
@@ -439,20 +439,20 @@ func TestNormalizerSubagentTask(t *testing.T) {
"subagent_type": "Explore",
}
result := normalizer.NormalizeToolCall(claudecode.ToolTask, args)
if result.Kind != streams.ToolKindSubagentTask {
t.Errorf("expected Kind %q, got %q", streams.ToolKindSubagentTask, result.Kind)
if result.Kind() != streams.ToolKindSubagentTask {
t.Errorf("expected Kind %q, got %q", streams.ToolKindSubagentTask, result.Kind())
}
if result.SubagentTask == nil {
if result.SubagentTask() == nil {
t.Fatal("expected SubagentTask to be set")
}
if result.SubagentTask.Description != "Find all test files" {
t.Errorf("expected Description 'Find all test files', got %q", result.SubagentTask.Description)
if result.SubagentTask().Description != "Find all test files" {
t.Errorf("expected Description 'Find all test files', got %q", result.SubagentTask().Description)
}
if result.SubagentTask.Prompt != "Search for test files in the codebase" {
t.Errorf("expected Prompt 'Search for test files in the codebase', got %q", result.SubagentTask.Prompt)
if result.SubagentTask().Prompt != "Search for test files in the codebase" {
t.Errorf("expected Prompt 'Search for test files in the codebase', got %q", result.SubagentTask().Prompt)
}
if result.SubagentTask.SubagentType != "Explore" {
t.Errorf("expected SubagentType 'Explore', got %q", result.SubagentTask.SubagentType)
if result.SubagentTask().SubagentType != "Explore" {
t.Errorf("expected SubagentType 'Explore', got %q", result.SubagentTask().SubagentType)
}
}
@@ -465,17 +465,17 @@ func TestNormalizerCreateTask(t *testing.T) {
"description": "The login flow fails when...",
}
result := normalizer.NormalizeToolCall(claudecode.ToolTaskCreate, args)
if result.Kind != streams.ToolKindCreateTask {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCreateTask, result.Kind)
if result.Kind() != streams.ToolKindCreateTask {
t.Errorf("expected Kind %q, got %q", streams.ToolKindCreateTask, result.Kind())
}
if result.CreateTask == nil {
if result.CreateTask() == nil {
t.Fatal("expected CreateTask to be set")
}
if result.CreateTask.Title != "Fix authentication bug" {
t.Errorf("expected Title 'Fix authentication bug', got %q", result.CreateTask.Title)
if result.CreateTask().Title != "Fix authentication bug" {
t.Errorf("expected Title 'Fix authentication bug', got %q", result.CreateTask().Title)
}
if result.CreateTask.Description != "The login flow fails when..." {
t.Errorf("expected Description 'The login flow fails when...', got %q", result.CreateTask.Description)
if result.CreateTask().Description != "The login flow fails when..." {
t.Errorf("expected Description 'The login flow fails when...', got %q", result.CreateTask().Description)
}
}
@@ -489,28 +489,28 @@ func TestNormalizerManageTodos(t *testing.T) {
"status": "completed",
}
result := normalizer.NormalizeToolCall(claudecode.ToolTaskUpdate, args)
if result.Kind != streams.ToolKindManageTodos {
t.Errorf("expected Kind %q, got %q", streams.ToolKindManageTodos, result.Kind)
if result.Kind() != streams.ToolKindManageTodos {
t.Errorf("expected Kind %q, got %q", streams.ToolKindManageTodos, result.Kind())
}
if result.ManageTodos == nil {
if result.ManageTodos() == nil {
t.Fatal("expected ManageTodos to be set")
}
if result.ManageTodos.Operation != "update" {
t.Errorf("expected Operation 'update', got %q", result.ManageTodos.Operation)
if result.ManageTodos().Operation != "update" {
t.Errorf("expected Operation 'update', got %q", result.ManageTodos().Operation)
}
})
t.Run("TaskList operation", func(t *testing.T) {
args := map[string]any{}
result := normalizer.NormalizeToolCall(claudecode.ToolTaskList, args)
if result.Kind != streams.ToolKindManageTodos {
t.Errorf("expected Kind %q, got %q", streams.ToolKindManageTodos, result.Kind)
if result.Kind() != streams.ToolKindManageTodos {
t.Errorf("expected Kind %q, got %q", streams.ToolKindManageTodos, result.Kind())
}
if result.ManageTodos == nil {
if result.ManageTodos() == nil {
t.Fatal("expected ManageTodos to be set")
}
if result.ManageTodos.Operation != "list" {
t.Errorf("expected Operation 'list', got %q", result.ManageTodos.Operation)
if result.ManageTodos().Operation != "list" {
t.Errorf("expected Operation 'list', got %q", result.ManageTodos().Operation)
}
})
@@ -525,20 +525,20 @@ func TestNormalizerManageTodos(t *testing.T) {
},
}
result := normalizer.NormalizeToolCall(claudecode.ToolTodoWrite, args)
if result.Kind != streams.ToolKindManageTodos {
t.Errorf("expected Kind %q, got %q", streams.ToolKindManageTodos, result.Kind)
if result.Kind() != streams.ToolKindManageTodos {
t.Errorf("expected Kind %q, got %q", streams.ToolKindManageTodos, result.Kind())
}
if result.ManageTodos == nil {
if result.ManageTodos() == nil {
t.Fatal("expected ManageTodos to be set")
}
if result.ManageTodos.Operation != "write" {
t.Errorf("expected Operation 'write', got %q", result.ManageTodos.Operation)
if result.ManageTodos().Operation != "write" {
t.Errorf("expected Operation 'write', got %q", result.ManageTodos().Operation)
}
if len(result.ManageTodos.Items) != 1 {
t.Fatalf("expected 1 item, got %d", len(result.ManageTodos.Items))
if len(result.ManageTodos().Items) != 1 {
t.Fatalf("expected 1 item, got %d", len(result.ManageTodos().Items))
}
if result.ManageTodos.Items[0].ID != "todo-1" {
t.Errorf("expected item ID 'todo-1', got %q", result.ManageTodos.Items[0].ID)
if result.ManageTodos().Items[0].ID != "todo-1" {
t.Errorf("expected item ID 'todo-1', got %q", result.ManageTodos().Items[0].ID)
}
})
}
@@ -551,14 +551,14 @@ func TestNormalizerGeneric(t *testing.T) {
"custom_field": "custom_value",
}
result := normalizer.NormalizeToolCall("UnknownTool", args)
if result.Kind != streams.ToolKindGeneric {
t.Errorf("expected Kind %q, got %q", streams.ToolKindGeneric, result.Kind)
if result.Kind() != streams.ToolKindGeneric {
t.Errorf("expected Kind %q, got %q", streams.ToolKindGeneric, result.Kind())
}
if result.Generic == nil {
if result.Generic() == nil {
t.Fatal("expected Generic to be set")
}
if result.Generic.Name != "UnknownTool" {
t.Errorf("expected Name 'UnknownTool', got %q", result.Generic.Name)
if result.Generic().Name != "UnknownTool" {
t.Errorf("expected Name 'UnknownTool', got %q", result.Generic().Name)
}
}
@@ -567,58 +567,50 @@ func TestNormalizerToolResult(t *testing.T) {
normalizer := NewNormalizer()
t.Run("shell exec result from string", func(t *testing.T) {
payload := &streams.NormalizedPayload{
Kind: streams.ToolKindShellExec,
ShellExec: &streams.ShellExecPayload{Command: "ls"},
}
// Use factory function to create payload
payload := streams.NewShellExec("ls", "", "", 0, false)
normalizer.NormalizeToolResult(payload, "file1.txt\nfile2.txt")
if payload.ShellExec.Output == nil {
if payload.ShellExec().Output == nil {
t.Fatal("expected Output to be set")
}
if payload.ShellExec.Output.Stdout != "file1.txt\nfile2.txt" {
t.Errorf("expected Stdout 'file1.txt\\nfile2.txt', got %q", payload.ShellExec.Output.Stdout)
if payload.ShellExec().Output.Stdout != "file1.txt\nfile2.txt" {
t.Errorf("expected Stdout 'file1.txt\\nfile2.txt', got %q", payload.ShellExec().Output.Stdout)
}
})
t.Run("shell exec result from map", func(t *testing.T) {
payload := &streams.NormalizedPayload{
Kind: streams.ToolKindShellExec,
ShellExec: &streams.ShellExecPayload{Command: "npm test"},
}
// Use factory function to create payload
payload := streams.NewShellExec("npm test", "", "", 0, false)
normalizer.NormalizeToolResult(payload, map[string]any{
"stdout": "All tests passed",
"stderr": "",
"exit_code": float64(0),
})
if payload.ShellExec.Output == nil {
if payload.ShellExec().Output == nil {
t.Fatal("expected Output to be set")
}
if payload.ShellExec.Output.Stdout != "All tests passed" {
t.Errorf("expected Stdout 'All tests passed', got %q", payload.ShellExec.Output.Stdout)
if payload.ShellExec().Output.Stdout != "All tests passed" {
t.Errorf("expected Stdout 'All tests passed', got %q", payload.ShellExec().Output.Stdout)
}
if payload.ShellExec.Output.ExitCode != 0 {
t.Errorf("expected ExitCode 0, got %d", payload.ShellExec.Output.ExitCode)
if payload.ShellExec().Output.ExitCode != 0 {
t.Errorf("expected ExitCode 0, got %d", payload.ShellExec().Output.ExitCode)
}
})
t.Run("http request result", func(t *testing.T) {
payload := &streams.NormalizedPayload{
Kind: streams.ToolKindHttpRequest,
HttpRequest: &streams.HttpRequestPayload{URL: "https://example.com"},
}
// Use factory function to create payload
payload := streams.NewHttpRequest("https://example.com", "GET")
normalizer.NormalizeToolResult(payload, "Response body here")
if payload.HttpRequest.Response != "Response body here" {
t.Errorf("expected Response 'Response body here', got %q", payload.HttpRequest.Response)
if payload.HttpRequest().Response != "Response body here" {
t.Errorf("expected Response 'Response body here', got %q", payload.HttpRequest().Response)
}
})
t.Run("generic result", func(t *testing.T) {
payload := &streams.NormalizedPayload{
Kind: streams.ToolKindGeneric,
Generic: &streams.GenericPayload{Name: "CustomTool"},
}
// Use factory function to create payload
payload := streams.NewGeneric("CustomTool", nil)
normalizer.NormalizeToolResult(payload, map[string]any{"data": "value"})
if payload.Generic.Output == nil {
if payload.Generic().Output == nil {
t.Fatal("expected Output to be set")
}
})
@@ -1147,9 +1147,18 @@ func (wt *WorkspaceTracker) buildFileTreeNode(fullPath, relPath string, info os.
// GetFileContent returns the content of a file
func (wt *WorkspaceTracker) GetFileContent(reqPath string) (string, int64, error) {
// Resolve the full path with path traversal protection
fullPath := filepath.Join(wt.workDir, filepath.Clean(reqPath))
cleanWorkDir := filepath.Clean(wt.workDir)
cleanReqPath := filepath.Clean(reqPath)
// Resolve the full path - if already absolute and within workDir, use directly
var fullPath string
if filepath.IsAbs(cleanReqPath) && strings.HasPrefix(cleanReqPath, cleanWorkDir+string(os.PathSeparator)) {
fullPath = cleanReqPath
} else {
fullPath = filepath.Join(wt.workDir, cleanReqPath)
}
// Path traversal protection
if !strings.HasPrefix(fullPath, cleanWorkDir+string(os.PathSeparator)) && fullPath != cleanWorkDir {
return "", 0, fmt.Errorf("path traversal detected")
}
@@ -75,6 +75,10 @@ type AgentEvent struct {
// ToolCallID uniquely identifies the tool invocation.
ToolCallID string `json:"tool_call_id,omitempty"`
// ParentToolCallID identifies the parent Task tool call when this event
// comes from a subagent. Used for visual nesting in the UI.
ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
// ToolName is the name of the tool being invoked.
ToolName string `json:"tool_name,omitempty"`
@@ -1,5 +1,7 @@
package streams
import "encoding/json"
// ToolKind categorizes the normalized tool operation
type ToolKind string
@@ -19,50 +21,121 @@ const (
// NormalizedPayload is the normalized tool data (discriminated union).
// Exactly one of the kind-specific fields will be set based on Kind.
// Fields are unexported to enforce use of factory functions (NewReadFile, NewShellExec, etc.)
type NormalizedPayload struct {
Kind ToolKind `json:"kind"`
kind ToolKind
readFile *ReadFilePayload
modifyFile *ModifyFilePayload
shellExec *ShellExecPayload
codeSearch *CodeSearchPayload
httpRequest *HttpRequestPayload
generic *GenericPayload
createTask *CreateTaskPayload
subagentTask *SubagentTaskPayload
showPlan *ShowPlanPayload
manageTodos *ManageTodosPayload
misc *MiscPayload
}
// read_file
ReadFile *ReadFilePayload `json:"read_file,omitempty"`
// --- Getters for NormalizedPayload ---
// modify_file
ModifyFile *ModifyFilePayload `json:"modify_file,omitempty"`
func (p *NormalizedPayload) Kind() ToolKind { return p.kind }
func (p *NormalizedPayload) ReadFile() *ReadFilePayload { return p.readFile }
func (p *NormalizedPayload) ModifyFile() *ModifyFilePayload { return p.modifyFile }
func (p *NormalizedPayload) ShellExec() *ShellExecPayload { return p.shellExec }
func (p *NormalizedPayload) CodeSearch() *CodeSearchPayload { return p.codeSearch }
func (p *NormalizedPayload) HttpRequest() *HttpRequestPayload { return p.httpRequest }
func (p *NormalizedPayload) Generic() *GenericPayload { return p.generic }
func (p *NormalizedPayload) CreateTask() *CreateTaskPayload { return p.createTask }
func (p *NormalizedPayload) SubagentTask() *SubagentTaskPayload { return p.subagentTask }
func (p *NormalizedPayload) ShowPlan() *ShowPlanPayload { return p.showPlan }
func (p *NormalizedPayload) ManageTodos() *ManageTodosPayload { return p.manageTodos }
func (p *NormalizedPayload) Misc() *MiscPayload { return p.misc }
// shell_exec
ShellExec *ShellExecPayload `json:"shell_exec,omitempty"`
// MarshalJSON implements custom JSON marshaling for NormalizedPayload.
func (p *NormalizedPayload) MarshalJSON() ([]byte, error) {
type jsonPayload struct {
Kind ToolKind `json:"kind"`
ReadFile *ReadFilePayload `json:"read_file,omitempty"`
ModifyFile *ModifyFilePayload `json:"modify_file,omitempty"`
ShellExec *ShellExecPayload `json:"shell_exec,omitempty"`
CodeSearch *CodeSearchPayload `json:"code_search,omitempty"`
HttpRequest *HttpRequestPayload `json:"http_request,omitempty"`
Generic *GenericPayload `json:"generic,omitempty"`
CreateTask *CreateTaskPayload `json:"create_task,omitempty"`
SubagentTask *SubagentTaskPayload `json:"subagent_task,omitempty"`
ShowPlan *ShowPlanPayload `json:"show_plan,omitempty"`
ManageTodos *ManageTodosPayload `json:"manage_todos,omitempty"`
Misc *MiscPayload `json:"misc,omitempty"`
}
return json.Marshal(jsonPayload{
Kind: p.kind,
ReadFile: p.readFile,
ModifyFile: p.modifyFile,
ShellExec: p.shellExec,
CodeSearch: p.codeSearch,
HttpRequest: p.httpRequest,
Generic: p.generic,
CreateTask: p.createTask,
SubagentTask: p.subagentTask,
ShowPlan: p.showPlan,
ManageTodos: p.manageTodos,
Misc: p.misc,
})
}
// code_search
CodeSearch *CodeSearchPayload `json:"code_search,omitempty"`
// http_request
HttpRequest *HttpRequestPayload `json:"http_request,omitempty"`
// generic (fallback)
Generic *GenericPayload `json:"generic,omitempty"`
// create_task
CreateTask *CreateTaskPayload `json:"create_task,omitempty"`
// subagent_task
SubagentTask *SubagentTaskPayload `json:"subagent_task,omitempty"`
// show_plan
ShowPlan *ShowPlanPayload `json:"show_plan,omitempty"`
// manage_todos
ManageTodos *ManageTodosPayload `json:"manage_todos,omitempty"`
// misc
Misc *MiscPayload `json:"misc,omitempty"`
// UnmarshalJSON implements custom JSON unmarshaling for NormalizedPayload.
// This is required because the struct has unexported fields.
func (p *NormalizedPayload) UnmarshalJSON(data []byte) error {
type jsonPayload struct {
Kind ToolKind `json:"kind"`
ReadFile *ReadFilePayload `json:"read_file,omitempty"`
ModifyFile *ModifyFilePayload `json:"modify_file,omitempty"`
ShellExec *ShellExecPayload `json:"shell_exec,omitempty"`
CodeSearch *CodeSearchPayload `json:"code_search,omitempty"`
HttpRequest *HttpRequestPayload `json:"http_request,omitempty"`
Generic *GenericPayload `json:"generic,omitempty"`
CreateTask *CreateTaskPayload `json:"create_task,omitempty"`
SubagentTask *SubagentTaskPayload `json:"subagent_task,omitempty"`
ShowPlan *ShowPlanPayload `json:"show_plan,omitempty"`
ManageTodos *ManageTodosPayload `json:"manage_todos,omitempty"`
Misc *MiscPayload `json:"misc,omitempty"`
}
var jp jsonPayload
if err := json.Unmarshal(data, &jp); err != nil {
return err
}
p.kind = jp.Kind
p.readFile = jp.ReadFile
p.modifyFile = jp.ModifyFile
p.shellExec = jp.ShellExec
p.codeSearch = jp.CodeSearch
p.httpRequest = jp.HttpRequest
p.generic = jp.Generic
p.createTask = jp.CreateTask
p.subagentTask = jp.SubagentTask
p.showPlan = jp.ShowPlan
p.manageTodos = jp.ManageTodos
p.misc = jp.Misc
return nil
}
// --- Kind-specific payloads ---
// ReadFileOutput contains the result of a file read operation.
type ReadFileOutput struct {
Content string `json:"content,omitempty"`
LineCount int `json:"line_count,omitempty"`
Truncated bool `json:"truncated,omitempty"`
Language string `json:"language,omitempty"`
}
// ReadFilePayload contains normalized data for file read operations.
type ReadFilePayload struct {
FilePath string `json:"file_path"`
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
FilePath string `json:"file_path"`
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
Output *ReadFileOutput `json:"output,omitempty"`
}
// ModifyFilePayload contains normalized data for file modification operations.
@@ -111,12 +184,20 @@ type ShellExecOutput struct {
Stderr string `json:"stderr,omitempty"`
}
// CodeSearchOutput contains the result of a code search operation.
type CodeSearchOutput struct {
Files []string `json:"files,omitempty"`
FileCount int `json:"file_count,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
// CodeSearchPayload contains normalized data for code search operations.
type CodeSearchPayload struct {
Query string `json:"query,omitempty"`
Pattern string `json:"pattern,omitempty"`
Path string `json:"path,omitempty"`
Glob string `json:"glob,omitempty"`
Query string `json:"query,omitempty"`
Pattern string `json:"pattern,omitempty"`
Path string `json:"path,omitempty"`
Glob string `json:"glob,omitempty"`
Output *CodeSearchOutput `json:"output,omitempty"`
}
// HttpRequestPayload contains normalized data for HTTP request operations.
@@ -171,13 +252,14 @@ type MiscPayload struct {
Details any `json:"details,omitempty"`
}
// --- Constructor functions for NormalizedPayload ---
// --- Factory functions for NormalizedPayload ---
// These are the ONLY way to create NormalizedPayload instances.
// NewReadFile creates a NormalizedPayload for file read operations.
func NewReadFile(filePath string, offset, limit int) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindReadFile,
ReadFile: &ReadFilePayload{
kind: ToolKindReadFile,
readFile: &ReadFilePayload{
FilePath: filePath,
Offset: offset,
Limit: limit,
@@ -188,8 +270,8 @@ func NewReadFile(filePath string, offset, limit int) *NormalizedPayload {
// NewModifyFile creates a NormalizedPayload for file modification operations.
func NewModifyFile(filePath string, mutations []FileMutation) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindModifyFile,
ModifyFile: &ModifyFilePayload{
kind: ToolKindModifyFile,
modifyFile: &ModifyFilePayload{
FilePath: filePath,
Mutations: mutations,
},
@@ -199,8 +281,8 @@ func NewModifyFile(filePath string, mutations []FileMutation) *NormalizedPayload
// NewShellExec creates a NormalizedPayload for shell command execution.
func NewShellExec(command, workDir, description string, timeout int, background bool) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindShellExec,
ShellExec: &ShellExecPayload{
kind: ToolKindShellExec,
shellExec: &ShellExecPayload{
Command: command,
WorkDir: workDir,
Description: description,
@@ -213,8 +295,8 @@ func NewShellExec(command, workDir, description string, timeout int, background
// NewCodeSearch creates a NormalizedPayload for code search operations.
func NewCodeSearch(query, pattern, path, glob string) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindCodeSearch,
CodeSearch: &CodeSearchPayload{
kind: ToolKindCodeSearch,
codeSearch: &CodeSearchPayload{
Query: query,
Pattern: pattern,
Path: path,
@@ -226,8 +308,8 @@ func NewCodeSearch(query, pattern, path, glob string) *NormalizedPayload {
// NewHttpRequest creates a NormalizedPayload for HTTP request operations.
func NewHttpRequest(url, method string) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindHttpRequest,
HttpRequest: &HttpRequestPayload{
kind: ToolKindHttpRequest,
httpRequest: &HttpRequestPayload{
URL: url,
Method: method,
},
@@ -237,8 +319,8 @@ func NewHttpRequest(url, method string) *NormalizedPayload {
// NewGeneric creates a NormalizedPayload for unrecognized tools.
func NewGeneric(name string, input any) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindGeneric,
Generic: &GenericPayload{
kind: ToolKindGeneric,
generic: &GenericPayload{
Name: name,
Input: input,
},
@@ -248,8 +330,8 @@ func NewGeneric(name string, input any) *NormalizedPayload {
// NewCreateTask creates a NormalizedPayload for task creation operations.
func NewCreateTask(title, description string) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindCreateTask,
CreateTask: &CreateTaskPayload{
kind: ToolKindCreateTask,
createTask: &CreateTaskPayload{
Title: title,
Description: description,
},
@@ -259,8 +341,8 @@ func NewCreateTask(title, description string) *NormalizedPayload {
// NewSubagentTask creates a NormalizedPayload for subagent task invocations.
func NewSubagentTask(description, prompt, subagentType string) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindSubagentTask,
SubagentTask: &SubagentTaskPayload{
kind: ToolKindSubagentTask,
subagentTask: &SubagentTaskPayload{
Description: description,
Prompt: prompt,
SubagentType: subagentType,
@@ -271,8 +353,8 @@ func NewSubagentTask(description, prompt, subagentType string) *NormalizedPayloa
// NewShowPlan creates a NormalizedPayload for plan display operations.
func NewShowPlan(summary string, steps []string) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindShowPlan,
ShowPlan: &ShowPlanPayload{
kind: ToolKindShowPlan,
showPlan: &ShowPlanPayload{
Summary: summary,
Steps: steps,
},
@@ -282,8 +364,8 @@ func NewShowPlan(summary string, steps []string) *NormalizedPayload {
// NewManageTodos creates a NormalizedPayload for todo management operations.
func NewManageTodos(operation string, items []TodoItem) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindManageTodos,
ManageTodos: &ManageTodosPayload{
kind: ToolKindManageTodos,
manageTodos: &ManageTodosPayload{
Operation: operation,
Items: items,
},
@@ -293,8 +375,8 @@ func NewManageTodos(operation string, items []TodoItem) *NormalizedPayload {
// NewMisc creates a NormalizedPayload for miscellaneous operations.
func NewMisc(label string, details any) *NormalizedPayload {
return &NormalizedPayload{
Kind: ToolKindMisc,
Misc: &MiscPayload{
kind: ToolKindMisc,
misc: &MiscPayload{
Label: label,
Details: details,
},
@@ -0,0 +1,87 @@
package streams
import (
"encoding/json"
"testing"
)
func TestNormalizedPayloadMarshalRoundTrip(t *testing.T) {
tests := []struct {
name string
payload *NormalizedPayload
}{
{
name: "shell_exec",
payload: NewShellExec("ls -la", "/home/user", "list files", 30000, false),
},
{
name: "read_file",
payload: NewReadFile("/path/to/file.go", 0, 100),
},
{
name: "modify_file",
payload: NewModifyFile("/path/to/file.go", []FileMutation{{Type: MutationPatch, Diff: "- old\n+ new"}}),
},
{
name: "code_search",
payload: NewCodeSearch("query", "pattern", "/path", "*.go"),
},
{
name: "generic",
payload: NewGeneric("custom_tool", map[string]any{"key": "value"}),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Marshal
data, err := json.Marshal(tt.payload)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
// Unmarshal
var result NormalizedPayload
if err := json.Unmarshal(data, &result); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
// Check kind matches
if result.Kind() != tt.payload.Kind() {
t.Errorf("Kind mismatch: got %q, want %q", result.Kind(), tt.payload.Kind())
}
// Check specific fields based on kind
switch tt.payload.Kind() {
case ToolKindShellExec:
if result.ShellExec() == nil {
t.Error("ShellExec() is nil after unmarshal")
} else if result.ShellExec().Command != tt.payload.ShellExec().Command {
t.Errorf("ShellExec.Command mismatch: got %q, want %q",
result.ShellExec().Command, tt.payload.ShellExec().Command)
}
case ToolKindReadFile:
if result.ReadFile() == nil {
t.Error("ReadFile() is nil after unmarshal")
} else if result.ReadFile().FilePath != tt.payload.ReadFile().FilePath {
t.Errorf("ReadFile.FilePath mismatch: got %q, want %q",
result.ReadFile().FilePath, tt.payload.ReadFile().FilePath)
}
case ToolKindModifyFile:
if result.ModifyFile() == nil {
t.Error("ModifyFile() is nil after unmarshal")
} else if result.ModifyFile().FilePath != tt.payload.ModifyFile().FilePath {
t.Errorf("ModifyFile.FilePath mismatch: got %q, want %q",
result.ModifyFile().FilePath, tt.payload.ModifyFile().FilePath)
}
case ToolKindGeneric:
if result.Generic() == nil {
t.Error("Generic() is nil after unmarshal")
} else if result.Generic().Name != tt.payload.Generic().Name {
t.Errorf("Generic.Name mismatch: got %q, want %q",
result.Generic().Name, tt.payload.Generic().Name)
}
}
})
}
}
@@ -486,12 +486,15 @@ func (a *testMessageCreatorAdapter) CreateUserMessage(ctx context.Context, taskI
return err
}
func (a *testMessageCreatorAdapter) CreateToolCallMessage(ctx context.Context, taskID, toolCallID, title, status, agentSessionID, turnID string, normalized *streams.NormalizedPayload) error {
func (a *testMessageCreatorAdapter) CreateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, title, status, agentSessionID, turnID string, normalized *streams.NormalizedPayload) error {
metadata := map[string]interface{}{
"tool_call_id": toolCallID,
"title": title,
"status": status,
}
if parentToolCallID != "" {
metadata["parent_tool_call_id"] = parentToolCallID
}
if normalized != nil {
metadata["normalized"] = normalized
}
@@ -507,8 +510,8 @@ func (a *testMessageCreatorAdapter) CreateToolCallMessage(ctx context.Context, t
return err
}
func (a *testMessageCreatorAdapter) UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, status, result, agentSessionID, title string, normalized *streams.NormalizedPayload) error {
return a.svc.UpdateToolCallMessage(ctx, agentSessionID, toolCallID, status, result, title, normalized)
func (a *testMessageCreatorAdapter) UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, status, result, agentSessionID, title, turnID, msgType string, normalized *streams.NormalizedPayload) error {
return a.svc.UpdateToolCallMessageWithCreate(ctx, agentSessionID, toolCallID, parentToolCallID, status, result, title, normalized, taskID, turnID, msgType)
}
func (a *testMessageCreatorAdapter) CreateSessionMessage(ctx context.Context, taskID, content, agentSessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error {
@@ -8,6 +8,7 @@ import (
"go.uber.org/zap"
"github.com/kandev/kandev/internal/agent/lifecycle"
"github.com/kandev/kandev/internal/agentctl/types/streams"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
"github.com/kandev/kandev/internal/orchestrator/watcher"
@@ -15,6 +16,27 @@ import (
v1 "github.com/kandev/kandev/pkg/api/v1"
)
// toolKindToMessageType maps the normalized tool kind to a frontend message type.
func toolKindToMessageType(normalized *streams.NormalizedPayload) string {
if normalized == nil {
return "tool_call"
}
switch normalized.Kind() {
case streams.ToolKindReadFile:
return "tool_read"
case streams.ToolKindCodeSearch:
return "tool_search"
case streams.ToolKindModifyFile:
return "tool_edit"
case streams.ToolKindShellExec:
return "tool_execute"
case streams.ToolKindManageTodos:
return "todo"
default:
return "tool_call"
}
}
// Event handlers
func (s *Service) handleACPSessionCreated(ctx context.Context, data watcher.ACPSessionEventData) {
@@ -679,6 +701,7 @@ func (s *Service) handleToolCallEvent(ctx context.Context, payload *lifecycle.Ag
ctx,
payload.TaskID,
payload.Data.ToolCallID,
payload.Data.ParentToolCallID, // Pass parent for subagent nesting
payload.Data.ToolTitle,
payload.Data.ToolStatus,
payload.SessionID,
@@ -831,6 +854,9 @@ func (s *Service) handleToolUpdateEvent(ctx context.Context, payload *lifecycle.
return
}
// Determine message type from normalized payload for fallback creation
msgType := toolKindToMessageType(payload.Data.Normalized)
// Handle all status updates (running, complete, error)
switch payload.Data.ToolStatus {
case "running", "complete", "completed", "success", "error", "failed":
@@ -838,11 +864,14 @@ func (s *Service) handleToolUpdateEvent(ctx context.Context, payload *lifecycle.
ctx,
payload.TaskID,
payload.Data.ToolCallID,
payload.Data.ParentToolCallID, // Pass parent for subagent nesting
payload.Data.ToolStatus,
"", // result - no longer used, tool results in NormalizedPayload
payload.SessionID,
payload.Data.ToolTitle, // Include title from update event
payload.Data.Normalized, // Pass normalized tool data for message metadata
payload.Data.ToolTitle, // Include title from update event
s.getActiveTurnID(payload.SessionID), // Turn ID for fallback creation
msgType, // Message type for fallback creation
payload.Data.Normalized, // Pass normalized tool data for message metadata
); err != nil {
s.logger.Warn("failed to update tool call message",
zap.String("task_id", payload.TaskID),
@@ -57,10 +57,13 @@ type MessageCreator interface {
CreateUserMessage(ctx context.Context, taskID, content, agentSessionID, turnID string) error
// CreateToolCallMessage creates a message for a tool call.
// normalized contains the typed tool payload data.
CreateToolCallMessage(ctx context.Context, taskID, toolCallID, title, status, agentSessionID, turnID string, normalized *streams.NormalizedPayload) error
// parentToolCallID is the parent Task tool call ID for subagent nesting (empty for top-level).
CreateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, title, status, agentSessionID, turnID string, normalized *streams.NormalizedPayload) error
// UpdateToolCallMessage updates a tool call message's status and optionally its normalized data.
// If the message doesn't exist, it creates it using taskID, turnID, and msgType.
// normalized contains the typed tool payload data.
UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, status, result, agentSessionID, title string, normalized *streams.NormalizedPayload) error
// parentToolCallID is the parent Task tool call ID for subagent nesting (empty for top-level).
UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, status, result, agentSessionID, title, turnID, msgType string, normalized *streams.NormalizedPayload) error
CreateSessionMessage(ctx context.Context, taskID, content, agentSessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error
CreatePermissionRequestMessage(ctx context.Context, taskID, sessionID, pendingID, toolCallID, title, turnID string, options []map[string]interface{}, actionType string, actionDetails map[string]interface{}) (string, error)
UpdatePermissionMessage(ctx context.Context, sessionID, pendingID, status string) error
@@ -427,6 +427,9 @@ func (r *Repository) initSchema() error {
if err := r.ensureColumn("task_session_messages", "task_session_id", "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
if err := r.ensureColumn("task_session_messages", "turn_id", "TEXT DEFAULT ''"); err != nil {
return err
}
// Ensure container_id column exists for existing databases
if err := r.ensureColumn("task_sessions", "container_id", "TEXT NOT NULL DEFAULT ''"); err != nil {
@@ -220,7 +220,8 @@ func (r *Repository) DeleteMessage(ctx context.Context, id string) error {
return nil
}
// GetMessageByToolCallID retrieves a tool_call message by session ID and tool_call_id in metadata
// GetMessageByToolCallID retrieves a tool message by session ID and tool_call_id in metadata
// Searches all tool types: tool_call, tool_read, tool_edit, tool_execute, tool_search
func (r *Repository) GetMessageByToolCallID(ctx context.Context, sessionID, toolCallID string) (*models.Message, error) {
message := &models.Message{}
var requestsInput int
@@ -228,7 +229,8 @@ func (r *Repository) GetMessageByToolCallID(ctx context.Context, sessionID, tool
var metadataJSON string
err := r.db.QueryRowContext(ctx, `
SELECT id, task_session_id, task_id, turn_id, author_type, author_id, content, requests_input, type, metadata, created_at
FROM task_session_messages WHERE task_session_id = ? AND type = 'tool_call' AND json_extract(metadata, '$.tool_call_id') = ?
FROM task_session_messages WHERE task_session_id = ? AND type LIKE 'tool_%' AND json_extract(metadata, '$.tool_call_id') = ?
ORDER BY created_at ASC LIMIT 1
`, sessionID, toolCallID).Scan(&message.ID, &message.TaskSessionID, &message.TaskID, &message.TurnID, &message.AuthorType, &message.AuthorID,
&message.Content, &requestsInput, &messageType, &metadataJSON, &message.CreatedAt)
if err != nil {
+60 -8
View File
@@ -2002,8 +2002,16 @@ func (s *Service) AppendThinkingContent(ctx context.Context, messageID, addition
// UpdateToolCallMessage updates a tool call message's status, optionally title and normalized data.
// It includes retry logic to handle race conditions where the complete event
// may arrive before the message has been created by the start event.
// If the message is not found after retries and taskID/turnID/msgType are provided, it creates the message.
// The normalized parameter contains typed tool payload data that gets added to metadata.
func (s *Service) UpdateToolCallMessage(ctx context.Context, sessionID, toolCallID, status, result, title string, normalized *streams.NormalizedPayload) error {
return s.UpdateToolCallMessageWithCreate(ctx, sessionID, toolCallID, "", status, result, title, normalized, "", "", "")
}
// UpdateToolCallMessageWithCreate is like UpdateToolCallMessage but can create the message if not found.
// If taskID, turnID, and msgType are provided, the message will be created if it doesn't exist.
// parentToolCallID is used for subagent nesting (empty for top-level).
func (s *Service) UpdateToolCallMessageWithCreate(ctx context.Context, sessionID, toolCallID, parentToolCallID, status, result, title string, normalized *streams.NormalizedPayload, taskID, turnID, msgType string) error {
const maxRetries = 5
const retryDelay = 100 * time.Millisecond
@@ -2034,6 +2042,51 @@ func (s *Service) UpdateToolCallMessage(ctx context.Context, sessionID, toolCall
}
}
// If message not found and we have enough info to create it, do so
if err != nil && taskID != "" && msgType != "" {
s.logger.Info("tool call message not found, creating it",
zap.String("session_id", sessionID),
zap.String("tool_call_id", toolCallID),
zap.String("task_id", taskID),
zap.String("msg_type", msgType))
metadata := map[string]interface{}{
"tool_call_id": toolCallID,
"title": title,
"status": status,
}
// Add parent tool call ID for subagent nesting (if present)
if parentToolCallID != "" {
metadata["parent_tool_call_id"] = parentToolCallID
}
if normalized != nil {
metadata["normalized"] = normalized
}
msg, createErr := s.CreateMessage(ctx, &CreateMessageRequest{
TaskSessionID: sessionID,
TaskID: taskID,
TurnID: turnID,
Content: title,
AuthorType: "agent",
Type: msgType,
Metadata: metadata,
})
if createErr != nil {
s.logger.Error("failed to create tool call message as fallback",
zap.String("session_id", sessionID),
zap.String("tool_call_id", toolCallID),
zap.Error(createErr))
return createErr
}
s.logger.Info("created tool call message as fallback",
zap.String("message_id", msg.ID),
zap.String("tool_call_id", toolCallID),
zap.String("status", status))
return nil
}
if err != nil {
s.logger.Warn("tool call message not found for update after retries",
zap.String("session_id", sessionID),
@@ -2056,14 +2109,12 @@ func (s *Service) UpdateToolCallMessage(ctx context.Context, sessionID, toolCall
message.Metadata["normalized"] = normalized
}
// Update title if provided and current title is just the tool name (not yet filled)
// This handles the case where the first event only had the tool name
if title != "" {
currentTitle, _ := message.Metadata["title"].(string)
if currentTitle == "" || currentTitle == message.Metadata["tool_name"] {
message.Content = title
message.Metadata["title"] = title
}
// Update title/content if provided and different from current
// This handles the case where the first event only had the tool name (e.g., "bash")
// and subsequent events have the actual command/path (e.g., "ls" or "/path/to/file")
if title != "" && title != message.Content {
message.Content = title
message.Metadata["title"] = title
}
if err := s.repo.UpdateMessage(ctx, message); err != nil {
@@ -2330,6 +2381,7 @@ func (s *Service) publishMessageEvent(ctx context.Context, eventType string, mes
"message_id": message.ID,
"session_id": message.TaskSessionID,
"task_id": message.TaskID,
"turn_id": message.TurnID,
"author_type": string(message.AuthorType),
"author_id": message.AuthorID,
"content": models.StripSystemContent(message.Content),
+3
View File
@@ -56,6 +56,9 @@ type CLIMessage struct {
SessionID string `json:"session_id,omitempty"`
SessionStatus string `json:"session_status,omitempty"`
// For subagent context (when running inside a Task tool call)
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
// For assistant messages
Message *AssistantMessage `json:"message,omitempty"`
+1 -1
View File
@@ -135,7 +135,7 @@
* {
@apply border-border outline-ring/50;
scrollbar-width: thin;
scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
scrollbar-color: var(--scrollbar-thumb) transparent;
}
body {
@apply bg-background text-foreground;
+4 -4
View File
@@ -1,6 +1,6 @@
"use client"
import * as React from "react"
import { memo, useState } from "react"
import { IconCheck, IconSelector } from "@tabler/icons-react"
import { cn } from "@/lib/utils"
@@ -39,7 +39,7 @@ interface ComboboxProps {
triggerClassName?: string
}
export function Combobox({
export const Combobox = memo(function Combobox({
options,
value,
onValueChange,
@@ -51,7 +51,7 @@ export function Combobox({
className,
triggerClassName,
}: ComboboxProps) {
const [open, setOpen] = React.useState(false)
const [open, setOpen] = useState(false)
const selectedOption = options.find((option) => option.value === value)
@@ -113,4 +113,4 @@ export function Combobox({
</PopoverContent>
</Popover>
)
}
});
+21
View File
@@ -0,0 +1,21 @@
'use client';
type GridSpinnerProps = {
className?: string;
};
export function GridSpinner({ className }: GridSpinnerProps) {
return (
<span className={`spinner-grid ${className ?? ''}`} role="status" aria-label="Loading">
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
</span>
);
}
+267 -184
View File
@@ -1,6 +1,6 @@
'use client';
import { useEffect, useRef, useState, FormEvent } from 'react';
import { useEffect, useRef, useState, FormEvent, memo, useMemo, useCallback } from 'react';
import Link from 'next/link';
import { IconSettings } from '@tabler/icons-react';
import {
@@ -88,7 +88,7 @@ type RepositorySelectorProps = {
emptyMessage: string;
};
function RepositorySelector({
const RepositorySelector = memo(function RepositorySelector({
options,
value,
onValueChange,
@@ -110,7 +110,7 @@ function RepositorySelector({
className={disabled ? undefined : 'cursor-pointer'}
/>
);
}
});
type BranchOption = {
value: string;
@@ -128,7 +128,7 @@ type BranchSelectorProps = {
emptyMessage: string;
};
function BranchSelector({
const BranchSelector = memo(function BranchSelector({
options,
value,
onValueChange,
@@ -150,7 +150,7 @@ function BranchSelector({
className={disabled ? undefined : 'cursor-pointer'}
/>
);
}
});
type AgentSelectorProps = {
options: Array<{ value: string; label: string; renderLabel: () => React.ReactNode }>;
@@ -161,7 +161,7 @@ type AgentSelectorProps = {
triggerClassName?: string;
};
function AgentSelector({
const AgentSelector = memo(function AgentSelector({
options,
value,
onValueChange,
@@ -183,7 +183,122 @@ function AgentSelector({
triggerClassName={triggerClassName}
/>
);
}
});
// Memoized text inputs to prevent re-rendering the entire dialog on every keystroke
type TaskFormInputsProps = {
isSessionMode: boolean;
initialTitle: string;
initialDescription: string;
onTitleChange: (hasContent: boolean) => void;
onDescriptionChange: (hasContent: boolean) => void;
onKeyDown: (e: React.KeyboardEvent) => void;
titleValueRef: React.RefObject<{ getValue: () => string } | null>;
descriptionValueRef: React.RefObject<{ getValue: () => string } | null>;
};
const TaskFormInputs = memo(function TaskFormInputs({
isSessionMode,
initialTitle,
initialDescription,
onTitleChange,
onDescriptionChange,
onKeyDown,
titleValueRef,
descriptionValueRef,
}: TaskFormInputsProps) {
const [title, setTitle] = useState(initialTitle);
const [description, setDescription] = useState(initialDescription);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Expose getValue methods via refs passed from parent
// This is an imperative handle pattern - refs are intentionally mutated
useEffect(() => {
const ref = titleValueRef as React.MutableRefObject<{ getValue: () => string } | null>;
if (ref) {
ref.current = { getValue: () => title };
}
}, [title, titleValueRef]);
useEffect(() => {
const ref = descriptionValueRef as React.MutableRefObject<{ getValue: () => string } | null>;
if (ref) {
// eslint-disable-next-line react-hooks/immutability
ref.current = { getValue: () => description };
}
}, [description, descriptionValueRef]);
// Auto-resize textarea
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = 'auto';
textarea.style.height = `${textarea.scrollHeight}px`;
}, [description]);
const handleTitleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
const hadContent = title.trim().length > 0;
const hasContent = newValue.trim().length > 0;
setTitle(newValue);
if (hadContent !== hasContent) {
onTitleChange(hasContent);
}
}, [title, onTitleChange]);
const handleDescriptionChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newValue = e.target.value;
const hadContent = description.trim().length > 0;
const hasContent = newValue.trim().length > 0;
setDescription(newValue);
if (hadContent !== hasContent) {
onDescriptionChange(hasContent);
}
}, [description, onDescriptionChange]);
return (
<>
{!isSessionMode && (
<div>
<Input
autoFocus
required
placeholder="Enter task title..."
value={title}
onChange={handleTitleChange}
disabled={isSessionMode}
/>
</div>
)}
{isSessionMode && (
<div>
<Label htmlFor="task-title">Task</Label>
<Input
id="task-title"
value={title}
disabled
placeholder="Task"
className="bg-muted cursor-not-allowed mt-1.5"
/>
</div>
)}
<div>
{isSessionMode && <Label htmlFor="prompt">Prompt</Label>}
<Textarea
id={isSessionMode ? 'prompt' : undefined}
ref={textareaRef}
placeholder={isSessionMode ? 'Describe what you want the agent to do...' : 'Write a prompt for the agent...'}
value={description}
onChange={handleDescriptionChange}
onKeyDown={onKeyDown}
rows={2}
className={isSessionMode ? 'min-h-[120px] resize-none mt-1.5' : 'min-h-[96px] max-h-[240px] resize-y overflow-auto'}
required={isSessionMode}
/>
</div>
</>
);
});
export function TaskCreateDialog({
open,
@@ -201,8 +316,12 @@ export function TaskCreateDialog({
}: TaskCreateDialogProps) {
const isSessionMode = mode === 'session';
const isEditMode = submitLabel !== 'Create';
const [title, setTitle] = useState(initialValues?.title ?? '');
const [description, setDescription] = useState(initialValues?.description ?? '');
// Track only whether inputs have content (not the actual values) to minimize re-renders
const [hasTitle, setHasTitle] = useState(Boolean(initialValues?.title?.trim()));
const [hasDescription, setHasDescription] = useState(Boolean(initialValues?.description?.trim()));
// Refs to get actual values when needed
const titleInputRef = useRef<{ getValue: () => string } | null>(null);
const descriptionInputRef = useRef<{ getValue: () => string } | null>(null);
const [repositoryId, setRepositoryId] = useState(initialValues?.repositoryId ?? '');
const [branch, setBranch] = useState(initialValues?.branch ?? '');
const [startAgent, setStartAgent] = useState(!isEditMode);
@@ -222,7 +341,6 @@ export function TaskCreateDialog({
const executors = useAppStore((state) => state.executors.items);
const environments = useAppStore((state) => state.environments.items);
const settingsData = useAppStore((state) => state.settingsData);
const descriptionRef = useRef<HTMLTextAreaElement | null>(null);
const { toast } = useToast();
useSettingsData(open);
const { repositories, isLoading: repositoriesLoading } = useRepositories(workspaceId, open);
@@ -236,8 +354,8 @@ export function TaskCreateDialog({
useEffect(() => {
if (!open) return;
setTitle(initialValues?.title ?? '');
setDescription(initialValues?.description ?? '');
setHasTitle(Boolean(initialValues?.title?.trim()));
setHasDescription(Boolean(initialValues?.description?.trim()));
setRepositoryId(initialValues?.repositoryId ?? '');
setBranch(initialValues?.branch ?? '');
setStartAgent(!isEditMode);
@@ -314,59 +432,124 @@ export function TaskCreateDialog({
}
}, [branch, branches, repositoryId]);
const handleSelectLocalRepository = (path: string) => {
const handleSelectLocalRepository = useCallback((path: string) => {
const selected = discoveredRepositories.find((repo) => repo.path === path) ?? null;
setDiscoveredRepoPath(path);
setSelectedLocalRepo(selected);
setRepositoryId('');
setBranch('');
setLocalBranches([]);
};
}, [discoveredRepositories]);
// Memoized callback for RepositorySelector to prevent re-renders when typing
const handleRepositoryChange = useCallback((value: string) => {
const workspaceRepo = repositories.find((repo: Repository) => repo.id === value);
if (workspaceRepo) {
setRepositoryId(value);
setDiscoveredRepoPath('');
setSelectedLocalRepo(null);
setLocalBranches([]);
setBranch('');
return;
}
handleSelectLocalRepository(value);
}, [repositories, handleSelectLocalRepository]);
const hasRepositorySelection = Boolean(repositoryId || selectedLocalRepo);
const branchOptions = repositoryId
const branchOptionsRaw = repositoryId
? branches
: localBranches;
const normalizeRepoPath = (path: string) => path.replace(/\\/g, '/').replace(/\/+$/g, '');
const workspaceRepoPaths = new Set(
repositories
.map((repo: Repository) => repo.local_path)
.filter(Boolean)
.map((path: string) => normalizeRepoPath(path))
);
const localRepoOptions = discoveredRepositories.filter(
(repo: LocalRepository) => !workspaceRepoPaths.has(normalizeRepoPath(repo.path))
);
const repositoryOptions: RepositoryOption[] = [
...repositories.map((repo: Repository) => ({
value: repo.id,
label: repo.name,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
<span className="shrink-0">{repo.name}</span>
<Badge
variant="secondary"
className="text-xs text-muted-foreground max-w-[140px] min-w-0 truncate ml-auto"
title={formatUserHomePath(repo.local_path)}
// Memoize repository options to prevent re-renders when typing
const repositoryOptions = useMemo(() => {
const normalizeRepoPath = (path: string) => path.replace(/\\/g, '/').replace(/\/+$/g, '');
const workspaceRepoPaths = new Set(
repositories
.map((repo: Repository) => repo.local_path)
.filter(Boolean)
.map((path: string) => normalizeRepoPath(path))
);
const localRepoOptions = discoveredRepositories.filter(
(repo: LocalRepository) => !workspaceRepoPaths.has(normalizeRepoPath(repo.path))
);
return [
...repositories.map((repo: Repository) => ({
value: repo.id,
label: repo.name,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
<span className="shrink-0">{repo.name}</span>
<Badge
variant="secondary"
className="text-xs text-muted-foreground max-w-[140px] min-w-0 truncate ml-auto"
title={formatUserHomePath(repo.local_path)}
>
{truncateRepoPath(repo.local_path, 24)}
</Badge>
</span>
),
})),
...localRepoOptions.map((repo: LocalRepository) => ({
value: repo.path,
label: truncateRepoPath(repo.path, 24),
renderLabel: () => (
<span
className="flex min-w-0 flex-1 items-center overflow-hidden"
title={formatUserHomePath(repo.path)}
>
{truncateRepoPath(repo.local_path, 24)}
</Badge>
</span>
),
})),
...localRepoOptions.map((repo: LocalRepository) => ({
value: repo.path,
label: truncateRepoPath(repo.path, 24),
renderLabel: () => (
<span
className="flex min-w-0 flex-1 items-center overflow-hidden"
title={formatUserHomePath(repo.path)}
>
<span className="truncate">{truncateRepoPath(repo.path, 28)}</span>
</span>
),
})),
];
<span className="truncate">{truncateRepoPath(repo.path, 28)}</span>
</span>
),
})),
];
}, [repositories, discoveredRepositories]);
// Memoize branch options to prevent re-renders when typing
const branchOptions = useMemo(() => {
return branchOptionsRaw.map((branchObj: Branch) => {
const displayName =
branchObj.type === 'remote' && branchObj.remote
? `${branchObj.remote}/${branchObj.name}`
: branchObj.name;
return {
value: displayName,
label: displayName,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate" title={displayName}>
{displayName}
</span>
<Badge variant={branchObj.type === 'local' ? 'default' : 'secondary'} className="text-xs">
{branchObj.type === 'local' ? 'local' : branchObj.remote || 'remote'}
</Badge>
</span>
),
};
});
}, [branchOptionsRaw]);
// Memoize agent profile options to prevent re-renders when typing
const agentProfileOptions = useMemo(() => {
return agentProfiles.map((profile: AgentProfileOption) => {
const parts = profile.label.split(' • ');
const agentLabel = parts[0] ?? profile.label;
const profileLabel = parts[1] ?? '';
return {
value: profile.id,
label: profile.label,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate">{agentLabel}</span>
{profileLabel ? (
<Badge variant="secondary" className="text-xs">
{profileLabel}
</Badge>
) : null}
</span>
),
};
});
}, [agentProfiles]);
useEffect(() => {
if (!open || !workspaceId || !selectedLocalRepo) return;
@@ -440,13 +623,6 @@ export function TaskCreateDialog({
setExecutorId(localExecutor?.id ?? executors[0].id);
}, [open, isEditMode, executorId, executors, workspaceDefaults, isSessionMode, startAgent]);
useEffect(() => {
const textarea = descriptionRef.current;
if (!textarea) return;
textarea.style.height = 'auto';
textarea.style.height = `${textarea.scrollHeight}px`;
}, [description]);
// Use keyboard shortcut hook for Cmd+Enter / Ctrl+Enter
const handleKeyDown = useKeyboardShortcutHandler(SHORTCUTS.SUBMIT, (event) => {
handleSubmit(event as unknown as FormEvent);
@@ -455,6 +631,10 @@ export function TaskCreateDialog({
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
// Get values from refs
const title = titleInputRef.current?.getValue() ?? '';
const description = descriptionInputRef.current?.getValue() ?? '';
// Session mode - create a new session
if (isSessionMode) {
const trimmedDescription = description.trim();
@@ -468,7 +648,7 @@ export function TaskCreateDialog({
});
// Reset form
setDescription('');
setHasDescription(false);
setAgentProfileId('');
setExecutorId('');
setEnvironmentId('');
@@ -526,8 +706,8 @@ export function TaskCreateDialog({
onSuccess?.(updatedTask, 'edit', { taskSessionId });
} finally {
setTitle('');
setDescription('');
setHasTitle(false);
setHasDescription(false);
setRepositoryId('');
setBranch('');
setStartAgent(false);
@@ -587,8 +767,8 @@ export function TaskCreateDialog({
taskSessionId: taskResponse.session_id ?? null,
});
} finally {
setTitle('');
setDescription('');
setHasTitle(false);
setHasDescription(false);
setRepositoryId('');
setBranch('');
setStartAgent(!isEditMode);
@@ -600,8 +780,8 @@ export function TaskCreateDialog({
};
const handleCancel = () => {
setTitle('');
setDescription('');
setHasTitle(false);
setHasDescription(false);
setRepositoryId('');
setBranch('');
setStartAgent(!isEditMode);
@@ -621,62 +801,24 @@ export function TaskCreateDialog({
</DialogHeader>
<form onSubmit={handleSubmit} className="flex flex-col gap-4 overflow-hidden">
<div className="flex-1 space-y-4 overflow-y-auto pr-1">
{!isSessionMode && (
<div>
<Input
autoFocus
required
placeholder="Enter task title..."
value={title}
onChange={(e) => setTitle(e.target.value)}
disabled={isSessionMode}
/>
</div>
)}
{isSessionMode && (
<div>
<Label htmlFor="task-title">Task</Label>
<Input
id="task-title"
value={title}
disabled
placeholder="Task"
className="bg-muted cursor-not-allowed mt-1.5"
/>
</div>
)}
<div>
{isSessionMode && <Label htmlFor="prompt">Prompt</Label>}
<Textarea
id={isSessionMode ? 'prompt' : undefined}
ref={descriptionRef}
placeholder={isSessionMode ? 'Describe what you want the agent to do...' : 'Write a prompt for the agent...'}
value={description}
onChange={(e) => setDescription(e.target.value)}
onKeyDown={handleKeyDown}
rows={2}
className={isSessionMode ? 'min-h-[120px] resize-none mt-1.5' : 'min-h-[96px] max-h-[240px] resize-y overflow-auto'}
required={isSessionMode}
/>
</div>
<TaskFormInputs
key={`${open}-${initialValues?.title ?? ''}-${initialValues?.description ?? ''}`}
isSessionMode={isSessionMode}
initialTitle={initialValues?.title ?? ''}
initialDescription={initialValues?.description ?? ''}
onTitleChange={setHasTitle}
onDescriptionChange={setHasDescription}
onKeyDown={handleKeyDown}
titleValueRef={titleInputRef}
descriptionValueRef={descriptionInputRef}
/>
{!isSessionMode && (
<div className="grid gap-4 md:grid-cols-3">
<div>
<RepositorySelector
options={repositoryOptions}
value={repositoryId || discoveredRepoPath}
onValueChange={(value) => {
const workspaceRepo = repositories.find((repo: Repository) => repo.id === value);
if (workspaceRepo) {
setRepositoryId(value);
setDiscoveredRepoPath('');
setSelectedLocalRepo(null);
setLocalBranches([]);
setBranch('');
return;
}
handleSelectLocalRepository(value);
}}
onValueChange={handleRepositoryChange}
placeholder={
!workspaceId
? 'Select workspace first'
@@ -695,32 +837,9 @@ export function TaskCreateDialog({
</div>
<div>
<BranchSelector
options={branchOptions.map((branchObj: Branch) => {
const displayName =
branchObj.type === 'remote' && branchObj.remote
? `${branchObj.remote}/${branchObj.name}`
: branchObj.name;
// Use display name as unique value since it includes remote prefix
return {
value: displayName,
label: displayName,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate" title={displayName}>
{displayName}
</span>
<Badge variant={branchObj.type === 'local' ? 'default' : 'secondary'} className="text-xs">
{branchObj.type === 'local' ? 'local' : branchObj.remote || 'remote'}
</Badge>
</span>
),
};
})}
options={branchOptions}
value={branch}
onValueChange={(displayName) => {
// Store the full display name (e.g., "origin/master" or "master")
setBranch(displayName);
}}
onValueChange={setBranch}
placeholder={
!hasRepositorySelection
? 'Select repository first'
@@ -755,25 +874,7 @@ export function TaskCreateDialog({
</div>
) : (
<AgentSelector
options={agentProfiles.map((profile: AgentProfileOption) => ({
value: profile.id,
label: profile.label,
renderLabel: () => {
const parts = profile.label.split(' • ');
const agentLabel = parts[0] ?? profile.label;
const profileLabel = parts[1] ?? '';
return (
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate">{agentLabel}</span>
{profileLabel ? (
<Badge variant="secondary" className="text-xs">
{profileLabel}
</Badge>
) : null}
</span>
);
},
}))}
options={agentProfileOptions}
value={agentProfileId}
onValueChange={setAgentProfileId}
placeholder={
@@ -796,25 +897,7 @@ export function TaskCreateDialog({
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3">
<AgentSelector
options={agentProfiles.map((profile: AgentProfileOption) => ({
value: profile.id,
label: profile.label,
renderLabel: () => {
const parts = profile.label.split(' • ');
const agentLabel = parts[0] ?? profile.label;
const profileLabel = parts[1] ?? '';
return (
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate">{agentLabel}</span>
{profileLabel ? (
<Badge variant="secondary" className="text-xs">
{profileLabel}
</Badge>
) : null}
</span>
);
},
}))}
options={agentProfileOptions}
value={agentProfileId}
onValueChange={setAgentProfileId}
placeholder={agentProfilesLoading ? 'Loading agent profiles...' : 'Select agent profile'}
@@ -983,9 +1066,9 @@ export function TaskCreateDialog({
type="submit"
disabled={
isSessionMode
? !description.trim() || !agentProfileId
: !title.trim() ||
!description.trim() ||
? !hasDescription || !agentProfileId
: !hasTitle ||
!hasDescription ||
(!isEditMode && !repositoryId && !selectedLocalRepo) ||
(startAgent && !agentProfileId) ||
(isEditMode && startAgent && !editingTask?.repositoryId && !repositoryId)
@@ -1,13 +1,13 @@
'use client';
import { useRef, useCallback, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useRef, useCallback, useState, useEffect, memo, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import {
IconArrowUp,
IconBrain,
IconListCheck,
IconLoader2,
IconPlayerStopFilled,
} from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { Button } from '@kandev/ui/button';
import {
DropdownMenu,
@@ -30,6 +30,138 @@ import { useInlineMention } from '@/hooks/use-inline-mention';
import { useInlineSlash } from '@/hooks/use-inline-slash';
import type { Message } from '@/lib/types/http';
// Memoized toolbar to prevent re-renders on input value changes
type ChatInputToolbarProps = {
planModeEnabled: boolean;
onPlanModeChange: (enabled: boolean) => void;
sessionId: string | null;
taskId: string | null;
taskTitle?: string;
taskDescription: string;
isAgentBusy: boolean;
isDisabled: boolean;
isSending: boolean;
onCancel: () => void;
onSubmit: () => void;
};
const ChatInputToolbar = memo(function ChatInputToolbar({
planModeEnabled,
onPlanModeChange,
sessionId,
taskId,
taskTitle,
taskDescription,
isAgentBusy,
isDisabled,
isSending,
onCancel,
onSubmit,
}: ChatInputToolbarProps) {
return (
<div className="flex items-center gap-1 px-2 py-2 border-t border-border">
{/* Left: Plan, Thinking, Context */}
<div className="flex items-center gap-0.5">
{/* Plan mode toggle */}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className={cn(
'h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40',
planModeEnabled && 'bg-primary/15 text-primary'
)}
onClick={() => onPlanModeChange(!planModeEnabled)}
>
<IconListCheck className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Toggle plan mode</TooltipContent>
</Tooltip>
{/* Thinking level dropdown */}
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40"
>
<IconBrain className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent>Thinking level</TooltipContent>
</Tooltip>
<DropdownMenuContent align="start" side="top">
<DropdownMenuItem>High</DropdownMenuItem>
<DropdownMenuItem>Medium</DropdownMenuItem>
<DropdownMenuItem>Low</DropdownMenuItem>
<DropdownMenuItem>Off</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Spacer */}
<div className="flex-1" />
{/* Right: Sessions, Model, Submit */}
<div className="flex items-center gap-0.5 shrink-0">
<SessionsDropdown
taskId={taskId}
activeSessionId={sessionId}
taskTitle={taskTitle}
taskDescription={taskDescription}
/>
{/* Token usage display */}
<TokenUsageDisplay sessionId={sessionId} />
<ModelSelector sessionId={sessionId} />
{/* Submit/Stop button */}
<div className="ml-1">
<KeyboardShortcutTooltip shortcut={SHORTCUTS.SUBMIT} enabled={!isAgentBusy && !isDisabled}>
{isAgentBusy ? (
<Button
type="button"
variant="secondary"
size="icon"
className="h-7 w-7 rounded-full cursor-pointer bg-destructive/10 text-destructive hover:bg-destructive/20"
disabled={isDisabled}
onClick={onCancel}
>
<IconPlayerStopFilled className="h-3.5 w-3.5" />
</Button>
) : (
<Button
type="button"
variant="default"
size="icon"
className="h-7 w-7 rounded-full cursor-pointer"
disabled={isDisabled}
onClick={onSubmit}
>
{isSending ? (
<GridSpinner className="text-primary-foreground" />
) : (
<IconArrowUp className="h-4 w-4" />
)}
</Button>
)}
</KeyboardShortcutTooltip>
</div>
</div>
</div>
);
});
type ChatInputContainerProps = {
onSubmit: (message: string) => void;
sessionId: string | null;
@@ -67,12 +199,24 @@ export function ChatInputContainer({
const [value, setValue] = useState('');
const inputRef = useRef<RichTextInputHandle>(null);
// Use ref for value to keep handleSubmit stable (doesn't change on every keystroke)
const valueRef = useRef(value);
useEffect(() => {
valueRef.current = value;
}, [value]);
// Mention menu hook
const mention = useInlineMention(inputRef, value, setValue, sessionId);
// Slash command menu hook
const slash = useInlineSlash(inputRef, value, setValue, onPlanModeChange);
// Use refs for menu state to keep handleSubmit stable
const menuStateRef = useRef({ mentionOpen: mention.isOpen, slashOpen: slash.isOpen });
useEffect(() => {
menuStateRef.current = { mentionOpen: mention.isOpen, slashOpen: slash.isOpen };
}, [mention.isOpen, slash.isOpen]);
// Combined change handler
const handleChange = useCallback(
(newValue: string) => {
@@ -98,15 +242,15 @@ export function ChatInputContainer({
[mention, slash]
);
// Handle form submission
// Stable submit handler using refs - doesn't change on value/menu state changes
const handleSubmit = useCallback(() => {
// Don't submit if a menu is open
if (mention.isOpen || slash.isOpen) return;
const trimmed = value.trim();
if (menuStateRef.current.mentionOpen || menuStateRef.current.slashOpen) return;
const trimmed = valueRef.current.trim();
if (!trimmed) return;
onSubmit(trimmed);
setValue('');
}, [mention.isOpen, slash.isOpen, value, onSubmit]);
}, [onSubmit]);
const isDisabled = isStarting || isSending;
const hasPendingClarification = pendingClarification && onClarificationResolved;
@@ -163,107 +307,20 @@ export function ChatInputContainer({
/>
)}
{/* Integrated toolbar */}
<div className="flex items-center gap-1 px-2 py-2 border-t border-border">
{/* Left: Plan, Thinking, Context */}
<div className="flex items-center gap-0.5">
{/* Plan mode toggle */}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className={cn(
'h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40',
planModeEnabled && 'bg-primary/15 text-primary'
)}
onClick={() => onPlanModeChange(!planModeEnabled)}
>
<IconListCheck className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Toggle plan mode</TooltipContent>
</Tooltip>
{/* Thinking level dropdown */}
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40"
>
<IconBrain className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent>Thinking level</TooltipContent>
</Tooltip>
<DropdownMenuContent align="start" side="top">
<DropdownMenuItem>High</DropdownMenuItem>
<DropdownMenuItem>Medium</DropdownMenuItem>
<DropdownMenuItem>Low</DropdownMenuItem>
<DropdownMenuItem>Off</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Spacer */}
<div className="flex-1" />
{/* Right: Sessions, Model, Submit */}
<div className="flex items-center gap-0.5 shrink-0">
<SessionsDropdown
taskId={taskId}
activeSessionId={sessionId}
taskTitle={taskTitle}
taskDescription={taskDescription}
/>
{/* Token usage display */}
<TokenUsageDisplay sessionId={sessionId} />
<ModelSelector sessionId={sessionId} />
{/* Submit/Stop button */}
<div className="ml-1">
<KeyboardShortcutTooltip shortcut={SHORTCUTS.SUBMIT} enabled={!isAgentBusy && !isStarting}>
{isAgentBusy ? (
<Button
type="button"
variant="secondary"
size="icon"
className="h-7 w-7 rounded-full cursor-pointer bg-destructive/10 text-destructive hover:bg-destructive/20"
disabled={isDisabled}
onClick={onCancel}
>
<IconPlayerStopFilled className="h-3.5 w-3.5" />
</Button>
) : (
<Button
type="button"
variant="default"
size="icon"
className="h-7 w-7 rounded-full cursor-pointer"
disabled={isDisabled}
onClick={handleSubmit}
>
{isSending ? (
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<IconArrowUp className="h-4 w-4" />
)}
</Button>
)}
</KeyboardShortcutTooltip>
</div>
</div>
</div>
{/* Integrated toolbar - memoized to prevent re-renders on input changes */}
<ChatInputToolbar
planModeEnabled={planModeEnabled}
onPlanModeChange={onPlanModeChange}
sessionId={sessionId}
taskId={taskId}
taskTitle={taskTitle}
taskDescription={taskDescription}
isAgentBusy={isAgentBusy}
isDisabled={isDisabled}
isSending={isSending}
onCancel={onCancel}
onSubmit={handleSubmit}
/>
</div>
);
}
@@ -1,23 +1,30 @@
'use client';
import type { ReactElement } from 'react';
import { memo, type ReactElement } from 'react';
import type { Message } from '@/lib/types/http';
import type { ToolCallMetadata } from '@/components/task/chat/types';
import { ChatMessage } from '@/components/task/chat/messages/chat-message';
import { PermissionRequestMessage } from '@/components/task/chat/messages/permission-request-message';
import { StatusMessage } from '@/components/task/chat/messages/status-message';
import { ToolCallMessage } from '@/components/task/chat/messages/tool-call-message';
import { ToolEditMessage } from '@/components/task/chat/messages/tool-edit-message';
import { ToolReadMessage } from '@/components/task/chat/messages/tool-read-message';
import { ToolSearchMessage } from '@/components/task/chat/messages/tool-search-message';
import { ToolExecuteMessage } from '@/components/task/chat/messages/tool-execute-message';
import { ThinkingMessage } from '@/components/task/chat/messages/thinking-message';
import { TodoMessage } from '@/components/task/chat/messages/todo-message';
import { ScriptExecutionMessage } from '@/components/task/chat/messages/script-execution-message';
import { ClarificationRequestMessage } from '@/components/task/chat/messages/clarification-request-message';
import { ToolSubagentMessage } from '@/components/task/chat/messages/tool-subagent-message';
type AdapterContext = {
isTaskDescription: boolean;
taskId?: string;
permissionsByToolCallId?: Map<string, Message>;
childrenByParentToolCallId?: Map<string, Message[]>;
worktreePath?: string;
sessionId?: string;
onOpenFile?: (path: string) => void;
};
type MessageAdapter = {
@@ -36,22 +43,59 @@ const adapters: MessageAdapter[] = [
},
{
matches: (comment) => comment.type === 'tool_edit',
render: (comment) => <ToolEditMessage comment={comment} />,
render: (comment, ctx) => <ToolEditMessage comment={comment} worktreePath={ctx.worktreePath} onOpenFile={ctx.onOpenFile} />,
},
{
matches: (comment) => comment.type === 'tool_read',
render: (comment) => <ToolReadMessage comment={comment} />,
render: (comment, ctx) => <ToolReadMessage comment={comment} worktreePath={ctx.worktreePath} sessionId={ctx.sessionId} onOpenFile={ctx.onOpenFile} />,
},
{
matches: (comment) => comment.type === 'tool_search',
render: (comment, ctx) => <ToolSearchMessage comment={comment} worktreePath={ctx.worktreePath} onOpenFile={ctx.onOpenFile} />,
},
{
matches: (comment) => comment.type === 'tool_execute',
render: (comment) => <ToolExecuteMessage comment={comment} />,
render: (comment, ctx) => <ToolExecuteMessage comment={comment} worktreePath={ctx.worktreePath} />,
},
{
// Subagent Task tool calls with nested children
matches: (comment, ctx) => {
if (comment.type !== 'tool_call') return false;
const metadata = comment.metadata as ToolCallMetadata | undefined;
const isSubagent = metadata?.normalized?.kind === 'subagent_task';
const toolCallId = metadata?.tool_call_id;
const hasChildren = toolCallId ? (ctx.childrenByParentToolCallId?.has(toolCallId) ?? false) : false;
return isSubagent || hasChildren;
},
render: (comment, ctx) => {
const toolCallId = (comment.metadata as ToolCallMetadata | undefined)?.tool_call_id;
const childMessages = toolCallId ? ctx.childrenByParentToolCallId?.get(toolCallId) ?? [] : [];
// Create a render function for child messages
const renderChild = (child: Message) => {
// Recursively use MessageRenderer for children (without subagent nesting)
const childCtx = { ...ctx, childrenByParentToolCallId: undefined };
const adapter = adapters.find((entry) => entry.matches(child, childCtx)) ?? adapters[adapters.length - 1];
return adapter.render(child, childCtx);
};
return (
<ToolSubagentMessage
comment={comment}
childMessages={childMessages}
worktreePath={ctx.worktreePath}
onOpenFile={ctx.onOpenFile}
renderChild={renderChild}
/>
);
},
},
{
matches: (comment) => comment.type === 'tool_call',
render: (comment, ctx) => {
const toolCallId = (comment.metadata as { tool_call_id?: string } | undefined)?.tool_call_id;
const permissionMessage = toolCallId ? ctx.permissionsByToolCallId?.get(toolCallId) : undefined;
return <ToolCallMessage comment={comment} permissionMessage={permissionMessage} />;
return <ToolCallMessage comment={comment} permissionMessage={permissionMessage} worktreePath={ctx.worktreePath} />;
},
},
{
@@ -110,10 +154,23 @@ type MessageRendererProps = {
isTaskDescription: boolean;
taskId?: string;
permissionsByToolCallId?: Map<string, Message>;
childrenByParentToolCallId?: Map<string, Message[]>;
worktreePath?: string;
sessionId?: string;
onOpenFile?: (path: string) => void;
};
export function MessageRenderer({ comment, isTaskDescription, taskId, permissionsByToolCallId }: MessageRendererProps) {
const ctx = { isTaskDescription, taskId, permissionsByToolCallId };
export const MessageRenderer = memo(function MessageRenderer({
comment,
isTaskDescription,
taskId,
permissionsByToolCallId,
childrenByParentToolCallId,
worktreePath,
sessionId,
onOpenFile,
}: MessageRendererProps) {
const ctx = { isTaskDescription, taskId, permissionsByToolCallId, childrenByParentToolCallId, worktreePath, sessionId, onOpenFile };
const adapter = adapters.find((entry) => entry.matches(comment, ctx)) ?? adapters[adapters.length - 1];
return adapter.render(comment, ctx);
}
});
@@ -4,6 +4,7 @@ import { useCallback, useMemo, useState, useEffect, useRef } from 'react';
import { IconAlertCircle, IconAlertTriangle, IconCopy, IconCheck } from '@tabler/icons-react';
import type { Message, TaskSessionState } from '@/lib/types/http';
import { useSessionTurn } from '@/hooks/domains/session/use-session-turn';
import { GridSpinner } from '@/components/grid-spinner';
type AgentStatusProps = {
sessionState?: TaskSessionState;
@@ -103,22 +104,6 @@ function useRunningTimer(isRunning: boolean) {
return { elapsedSeconds: displaySeconds, formatted };
}
function GridSpinner({ className }: { className?: string }) {
return (
<span className={`spinner-grid ${className ?? ''}`} role="status" aria-label="Loading">
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
<span className="spinner-grid-cube" />
</span>
);
}
function CopyButton({ content }: { content: string }) {
const [copied, setCopied] = useState(false);
@@ -208,9 +193,9 @@ export function AgentStatus({ sessionState, sessionId, messages = [] }: AgentSta
if (isRunning && config) {
return (
<div className="py-2" role="status" aria-label={config.label}>
<span className="inline-flex items-center gap-2 text-xs">
<GridSpinner className="text-primary" />
<span className="text-muted-foreground">{config.label}</span>
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
{config.label}
<GridSpinner className="text-muted-foreground" />
{elapsedSeconds > 0 && (
<span className="text-muted-foreground/60 tabular-nums">
{runningDuration}
@@ -1,5 +1,6 @@
'use client';
import { memo, isValidElement, type ReactNode } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
@@ -9,6 +10,34 @@ import { RichBlocks } from '@/components/task/chat/messages/rich-blocks';
import { InlineCode } from '@/components/task/chat/messages/inline-code';
import { CodeBlock } from '@/components/task/chat/messages/code-block';
/**
* Recursively extracts text content from React children.
* Optimized with fast paths for common cases (string/number).
*/
function getTextContent(children: ReactNode): string {
// Fast path: most common cases first
if (typeof children === 'string') return children;
if (typeof children === 'number') return String(children);
if (children == null) return '';
// Use loop instead of map().join() to avoid intermediate array allocation
if (Array.isArray(children)) {
let result = '';
for (let i = 0; i < children.length; i++) {
result += getTextContent(children[i]);
}
return result;
}
if (isValidElement(children)) {
const props = children.props as { children?: ReactNode };
if (props.children) {
return getTextContent(props.children);
}
}
return '';
}
type ChatMessageProps = {
comment: Message;
label: string;
@@ -58,7 +87,7 @@ function renderContentWithFileRefs(content: string): React.ReactNode[] {
return parts.length > 0 ? parts : [content];
}
export function ChatMessage({ comment, label, className, showRichBlocks }: ChatMessageProps) {
export const ChatMessage = memo(function ChatMessage({ comment, label, className, showRichBlocks }: ChatMessageProps) {
const isUser = comment.author_type === 'user';
const isTaskDescription = label === 'Task';
@@ -87,7 +116,7 @@ export function ChatMessage({ comment, label, className, showRichBlocks }: ChatM
return (
<div className="flex justify-end w-full overflow-hidden">
<div className="max-w-[85%] sm:max-w-[75%] md:max-w-2xl overflow-hidden">
<div className="rounded-2xl border-primary/30 bg-primary/10 px-4 py-2.5 text-xs overflow-hidden">
<div className="rounded-2xl bg-primary/30 px-4 py-2.5 text-xs overflow-hidden">
<p className="whitespace-pre-wrap break-words overflow-wrap-anywhere">
{comment.content ? renderContentWithFileRefs(comment.content) : '(empty)'}
</p>
@@ -108,59 +137,60 @@ export function ChatMessage({ comment, label, className, showRichBlocks }: ChatM
remarkPlugins={[remarkGfm, remarkBreaks]}
components={{
code: ({ className, children }) => {
// Check if it's inline code (no className means inline, className with language-* means code block)
const isInline = !className || !className.startsWith('language-');
const content = getTextContent(children).replace(/\n$/, '');
const hasLanguage = className?.startsWith('language-');
const hasNewlines = content.includes('\n');
// Inline code (backticks) - with copy on click
if (isInline) {
return <InlineCode>{children}</InlineCode>;
// Code block if it has a language specifier OR has multiple lines
if (hasLanguage || hasNewlines) {
return <CodeBlock className={className}>{content}</CodeBlock>;
}
// Code blocks (triple backticks) - with syntax highlighting and copy button
return <CodeBlock className={className}>{children}</CodeBlock>;
// Inline code (single backticks, single line)
return <InlineCode>{content}</InlineCode>;
},
ol: ({ children, ...props }) => (
<ol className="list-decimal pl-6" {...props}>
ol: ({ children }) => (
<ol className="list-decimal pl-6 my-2">
{children}
</ol>
),
ul: ({ children, ...props }) => (
<ul className="list-disc pl-6" {...props}>
ul: ({ children }) => (
<ul className="list-disc pl-6 my-1">
{children}
</ul>
),
li: ({ children, ...props }) => (
<li className="my-1" {...props}>
li: ({ children }) => (
<li className="my-0.5">
{children}
</li>
),
p: ({ children, ...props }) => (
<p className="leading-relaxed" {...props}>
p: ({ children }) => (
<p className="leading-relaxed my-0.5">
{children}
</p>
),
h1: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
h1: ({ children }) => (
<p className="my-3 font-bold text-[13px]">
{children}
</p>
),
h2: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
h2: ({ children }) => (
<p className="my-2 font-bold text-[13px]">
{children}
</p>
),
h3: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
h3: ({ children }) => (
<p className="my-2 font-bold">
{children}
</p>
),
h4: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
h4: ({ children }) => (
<p className="my-2 font-bold">
{children}
</p>
),
h5: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
h5: ({ children }) => (
<p className="my-2 font-bold">
{children}
</p>
),
@@ -173,4 +203,4 @@ export function ChatMessage({ comment, label, className, showRichBlocks }: ChatM
</div>
</div>
);
}
});
@@ -3,82 +3,21 @@
import { useState } from 'react';
import { useTheme } from 'next-themes';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import { go } from '@codemirror/lang-go';
import { rust } from '@codemirror/lang-rust';
import { java } from '@codemirror/lang-java';
import { cpp } from '@codemirror/lang-cpp';
import { css } from '@codemirror/lang-css';
import { html } from '@codemirror/lang-html';
import { json } from '@codemirror/lang-json';
import { markdown } from '@codemirror/lang-markdown';
import { yaml } from '@codemirror/lang-yaml';
import { vscodeDark, vscodeLight } from '@uiw/codemirror-theme-vscode';
import { EditorView } from '@codemirror/view';
import { IconCheck, IconCopy } from '@tabler/icons-react';
import type { Extension } from '@codemirror/state';
import { cn } from '@/lib/utils';
import { getCodeMirrorExtension } from '@/lib/languages';
type CodeBlockProps = {
children: React.ReactNode;
className?: string;
};
const getLanguageExtension = (language?: string): Extension | undefined => {
const getLanguageExtension = (language?: string) => {
if (!language) return undefined;
const lang = language.replace('language-', '').toLowerCase();
switch (lang) {
case 'javascript':
case 'js':
return javascript();
case 'jsx':
return javascript({ jsx: true });
case 'typescript':
case 'ts':
return javascript({ typescript: true });
case 'tsx':
return javascript({ jsx: true, typescript: true });
case 'python':
case 'py':
return python();
case 'go':
case 'golang':
return go();
case 'rust':
case 'rs':
return rust();
case 'java':
return java();
case 'cpp':
case 'c++':
case 'c':
return cpp();
case 'css':
case 'scss':
case 'less':
return css();
case 'html':
case 'htm':
return html();
case 'json':
return json();
case 'markdown':
case 'md':
return markdown();
case 'yaml':
case 'yml':
return yaml();
case 'bash':
case 'sh':
case 'shell':
// Bash doesn't have a specific extension, fallback to basic
return undefined;
default:
return undefined;
}
return getCodeMirrorExtension(lang);
};
export function CodeBlock({ children, className }: CodeBlockProps) {
@@ -0,0 +1,72 @@
'use client';
import { ReactNode, memo, useCallback } from 'react';
import { IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
type ExpandableRowProps = {
/** The icon to display (will transition to chevron on hover when expandable) */
icon: ReactNode;
/** Header content displayed next to the icon */
header: ReactNode;
/** Whether there is expandable content */
hasExpandableContent: boolean;
/** Current expanded state */
isExpanded: boolean;
/** Callback when toggled */
onToggle: () => void;
/** Expanded content (rendered outside clickable area) */
children?: ReactNode;
};
export const ExpandableRow = memo(function ExpandableRow({
icon,
header,
hasExpandableContent,
isExpanded,
onToggle,
children,
}: ExpandableRowProps) {
const handleClick = useCallback(() => {
if (hasExpandableContent) onToggle();
}, [hasExpandableContent, onToggle]);
return (
<div className="w-full group">
{/* Clickable header row */}
<div
className={cn(
'flex items-start gap-3 w-full rounded px-2 py-1 -mx-2 transition-colors',
hasExpandableContent && 'hover:bg-muted/50 cursor-pointer'
)}
onClick={handleClick}
>
{/* Icon with hover-to-show chevron */}
<div className="flex-shrink-0 mt-0.5 relative w-4 h-4">
<div
className={cn(
'absolute inset-0 transition-opacity',
hasExpandableContent && 'group-hover:opacity-0'
)}
>
{icon}
</div>
{hasExpandableContent &&
(isExpanded ? (
<IconChevronDown className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
) : (
<IconChevronRight className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
))}
</div>
{/* Header content */}
<div className="flex-1 min-w-0 pt-0.5">{header}</div>
</div>
{/* Expanded content - outside clickable area */}
{isExpanded && hasExpandableContent && children && (
<div className="mt-2 ml-7">{children}</div>
)}
</div>
);
});
@@ -0,0 +1,70 @@
'use client';
import { memo, useCallback } from 'react';
import { cn, toRelativePath } from '@/lib/utils';
type FilePathButtonProps = {
filePath: string;
worktreePath?: string;
onOpenFile?: (path: string) => void;
variant?: 'badge' | 'list-item';
className?: string;
};
/**
* Check if a file path looks like a valid, openable file (not a directory or invalid path).
* Returns false for:
* - Empty paths or just whitespace
* - Single dot "." (current directory)
* - Paths ending with "/" (directories)
* - Paths without a file extension in the last segment (likely directories)
*/
function isOpenableFilePath(path: string): boolean {
if (!path || !path.trim()) return false;
const trimmed = path.trim();
if (trimmed === '.') return false;
if (trimmed.endsWith('/')) return false;
// Get the last segment of the path
const lastSegment = trimmed.split('/').pop() || '';
// If last segment has no extension and doesn't start with a dot (hidden file), it's likely a directory
if (!lastSegment.includes('.')) return false;
return true;
}
export const FilePathButton = memo(function FilePathButton({ filePath, worktreePath, onOpenFile, variant = 'badge', className = '' }: FilePathButtonProps) {
const relativePath = toRelativePath(filePath, worktreePath);
const canOpen = isOpenableFilePath(filePath);
const handleClick = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
onOpenFile?.(filePath);
}, [onOpenFile, filePath]);
const baseStyles = 'font-mono truncate cursor-pointer text-indigo-400 hover:underline transition-colors block w-full text-left';
const variantStyles = variant === 'badge'
? 'text-xs px-1.5 py-0.5 rounded bg-indigo-500/20 hover:bg-indigo-500/30'
: 'flex items-center px-2 py-1 rounded hover:bg-indigo-500/20';
if (onOpenFile && canOpen) {
return (
<button
type="button"
onClick={handleClick}
className={cn(baseStyles, variantStyles, className)}
title={filePath}
>
{relativePath}
</button>
);
}
const inactiveStyles = variant === 'badge'
? 'text-xs text-muted-foreground/60 truncate font-mono bg-muted/30 px-1.5 py-0.5 rounded block w-full'
: 'px-2 py-1 font-mono text-muted-foreground truncate block w-full';
return (
<span className={cn(inactiveStyles, className)} title={filePath}>
{relativePath}
</span>
);
});
@@ -32,8 +32,8 @@ export function InlineCode({ children }: InlineCodeProps) {
<code
onClick={handleClick}
className={cn(
'px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded font-mono text-[0.9em]',
'cursor-pointer hover:bg-blue-500/30 transition-colors'
'px-0.5 py-0.5 text-indigo-400 rounded font-mono',
'cursor-pointer hover:bg-indigo-500/30 transition-colors'
)}
>
{children}
@@ -1,6 +1,8 @@
'use client';
import { IconCheck, IconLoader2, IconX } from '@tabler/icons-react';
import { memo } from 'react';
import { IconCheck, IconX } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { Button } from '@kandev/ui/button';
type PermissionActionRowProps = {
@@ -9,7 +11,7 @@ type PermissionActionRowProps = {
isResponding?: boolean;
};
export function PermissionActionRow({
export const PermissionActionRow = memo(function PermissionActionRow({
onApprove,
onReject,
isResponding = false,
@@ -37,7 +39,7 @@ export function PermissionActionRow({
className="h-6 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
>
{isResponding ? (
<IconLoader2 className="h-4 w-4 mr-1 animate-spin" />
<GridSpinner className="text-foreground mr-1" />
) : (
<IconCheck className="h-4 w-4 mr-1 text-green-500" />
)}
@@ -45,4 +47,4 @@ export function PermissionActionRow({
</Button>
</div>
);
}
});
@@ -1,7 +1,8 @@
'use client';
import { useState } from 'react';
import { IconCheck, IconX, IconLoader2, IconTerminal, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { useState, memo } from 'react';
import { IconCheck, IconX, IconTerminal, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { cn } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import { Badge } from '@kandev/ui/badge';
@@ -17,41 +18,47 @@ interface ScriptExecutionMetadata {
error?: string;
}
export function ScriptExecutionMessage({ comment }: { comment: Message }) {
export const ScriptExecutionMessage = memo(function ScriptExecutionMessage({ comment }: { comment: Message }) {
const [isExpanded, setIsExpanded] = useState(false);
const metadata = comment.metadata as ScriptExecutionMetadata | undefined;
// Show fallback if metadata is missing or incomplete
if (!metadata || !metadata.script_type) {
const hasContent = !!comment.content;
const hasExpandableContent = !!comment.content;
return (
<div className="w-full">
<div className="flex items-start gap-3 w-full">
<div className="flex-shrink-0 mt-0.5">
<IconTerminal className="h-4 w-4 text-yellow-600 dark:text-yellow-400" />
<div className="w-full group">
<div
className={cn(
'flex items-start gap-3 w-full rounded px-2 py-1 -mx-2 transition-colors',
hasExpandableContent && 'hover:bg-muted/50 cursor-pointer'
)}
onClick={() => { if (hasExpandableContent) setIsExpanded(!isExpanded); }}
>
<div className={cn(
'flex-shrink-0 mt-0.5 relative w-4 h-4',
hasExpandableContent && 'cursor-pointer'
)}>
<IconTerminal className={cn(
'h-4 w-4 text-yellow-600 dark:text-yellow-400 absolute inset-0 transition-opacity',
hasExpandableContent && 'group-hover:opacity-0'
)} />
{hasExpandableContent && (
isExpanded
? <IconChevronDown className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
: <IconChevronRight className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
)}
</div>
<div className="flex-1 min-w-0">
<button
type="button"
onClick={() => hasContent && setIsExpanded(!isExpanded)}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasContent && 'cursor-pointer hover:opacity-70 transition-opacity'
)}
disabled={!hasContent}
>
<span className="text-xs font-mono text-yellow-600 dark:text-yellow-400">
Script Execution (metadata unavailable)
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5">
<span className="text-xs font-mono text-yellow-600 dark:text-yellow-400">
Script Execution (metadata unavailable)
</span>
</span>
{hasContent && (
isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)
)}
</button>
</div>
{isExpanded && comment.content && (
<div className="mt-2 pl-4 border-l-2 border-border/30">
<pre className="font-mono text-xs bg-muted/30 rounded px-3 py-2 overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
@@ -70,64 +77,54 @@ export function ScriptExecutionMessage({ comment }: { comment: Message }) {
const isRunning = status === 'starting' || status === 'running';
const isSuccess = status === 'exited' && exit_code === 0;
// Status icon and styling
const StatusIcon = isRunning
? IconLoader2
: isSuccess
? IconCheck
: IconX;
const statusColor = isRunning
? 'text-blue-500'
: isSuccess
? 'text-green-500'
: 'text-red-500';
const hasDetails = comment.content || error || exit_code !== undefined;
const StatusIcon = isSuccess ? IconCheck : IconX;
const statusColor = isSuccess ? 'text-green-500' : 'text-red-500';
const hasExpandableContent = !!(comment.content || error || exit_code !== undefined);
return (
<div className="w-full">
{/* Icon + Summary Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<IconTerminal className="h-4 w-4 text-muted-foreground" />
<div className="w-full group">
<div
className={cn(
'flex items-start gap-3 w-full rounded px-2 py-1 -mx-2 transition-colors',
hasExpandableContent && 'hover:bg-muted/50 cursor-pointer'
)}
onClick={() => { if (hasExpandableContent) setIsExpanded(!isExpanded); }}
>
{/* Icon with hover-to-show chevron */}
<div className={cn(
'flex-shrink-0 mt-0.5 relative w-4 h-4',
hasExpandableContent && 'cursor-pointer'
)}>
<IconTerminal className={cn(
'h-4 w-4 text-muted-foreground absolute inset-0 transition-opacity',
hasExpandableContent && 'group-hover:opacity-0'
)} />
{hasExpandableContent && (
isExpanded
? <IconChevronDown className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
: <IconChevronRight className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
)}
</div>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => hasDetails && setIsExpanded(!isExpanded)}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasDetails && 'cursor-pointer hover:opacity-70 transition-opacity'
)}
disabled={!hasDetails}
>
<span className="inline-flex items-center gap-1.5 shrink-0 whitespace-nowrap">
<Badge variant={isSetup ? 'default' : 'secondary'} className="text-xs">
{isSetup ? 'Setup' : 'Cleanup'}
</Badge>
<span className="font-mono text-xs text-muted-foreground">
{command}
</span>
{/* Status indicator - only show if not success */}
{!isSuccess && (
<StatusIcon className={cn('h-3.5 w-3.5', statusColor, isRunning && 'animate-spin')} />
{isRunning && <GridSpinner className="text-muted-foreground" />}
{!isSuccess && !isRunning && (
<StatusIcon className={cn('h-3.5 w-3.5', statusColor)} />
)}
{hasDetails && (
isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)
)}
</button>
</span>
</div>
{/* Expanded Details */}
{isExpanded && hasDetails && (
{isExpanded && hasExpandableContent && (
<div className="mt-2 pl-4 border-l-2 border-border/30 space-y-2">
{/* Output */}
{comment.content && comment.content.trim() !== '' && (
@@ -170,7 +167,7 @@ export function ScriptExecutionMessage({ comment }: { comment: Message }) {
</div>
</div>
);
}
});
// Helper function to calculate duration
function calculateDuration(startedAt: string, completedAt: string): string {
@@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useState, memo, useCallback } from 'react';
import { IconAlertTriangle, IconInfoCircle, IconHandStop, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
@@ -15,7 +15,7 @@ interface ErrorMetadata extends StatusMetadata {
provider_agent?: string;
}
export function StatusMessage({ comment }: { comment: Message }) {
export const StatusMessage = memo(function StatusMessage({ comment }: { comment: Message }) {
const [isExpanded, setIsExpanded] = useState(false);
const metadata = comment.metadata as ErrorMetadata | undefined;
const progress =
@@ -28,6 +28,39 @@ export function StatusMessage({ comment }: { comment: Message }) {
// Check if there are error details to show
const hasErrorDetails = isError && (metadata?.error_data || metadata?.error || metadata?.text || metadata?.stderr);
// Format error details for display
const formatErrorDetails = () => {
const details: { label: string; value: string }[] = [];
if (metadata?.stderr && metadata.stderr.length > 0) {
details.push({ label: 'Agent Output', value: metadata.stderr.join('\n') });
}
if (metadata?.error) {
details.push({ label: 'Error', value: metadata.error });
}
if (metadata?.text) {
details.push({ label: 'Details', value: metadata.text });
}
if (metadata?.error_data) {
// Don't show stderr again in error_data since we already show it above
const filteredData = { ...metadata.error_data };
delete filteredData.stderr;
if (Object.keys(filteredData).length > 0) {
details.push({ label: 'Error Data', value: JSON.stringify(filteredData, null, 2) });
}
}
return details;
};
const errorDetails = hasErrorDetails ? formatErrorDetails() : [];
const hasExpandableContent = hasErrorDetails && errorDetails.length > 0;
// useCallback must be called before any early returns (React hooks rules)
const handleToggle = useCallback(() => {
if (hasExpandableContent) setIsExpanded((prev) => !prev);
}, [hasExpandableContent]);
// Simple system message: no metadata, no progress, just a short message
const isSimpleStatus = !isError && !isWarning && progress === null && !statusLine && !metadata?.message;
@@ -59,40 +92,30 @@ export function StatusMessage({ comment }: { comment: Message }) {
const iconClass = isError ? 'text-red-500' : isWarning ? 'text-amber-500' : 'text-muted-foreground';
const textClass = isError ? 'text-red-600 dark:text-red-400' : isWarning ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground';
// Format error details for display
const formatErrorDetails = () => {
const details: { label: string; value: string }[] = [];
if (metadata?.stderr && metadata.stderr.length > 0) {
details.push({ label: 'Agent Output', value: metadata.stderr.join('\n') });
}
if (metadata?.error) {
details.push({ label: 'Error', value: metadata.error });
}
if (metadata?.text) {
details.push({ label: 'Details', value: metadata.text });
}
if (metadata?.error_data) {
// Don't show stderr again in error_data since we already show it above
const filteredData = { ...metadata.error_data };
delete filteredData.stderr;
if (Object.keys(filteredData).length > 0) {
details.push({ label: 'Error Data', value: JSON.stringify(filteredData, null, 2) });
}
}
return details;
};
const errorDetails = hasErrorDetails ? formatErrorDetails() : [];
return (
<div className="w-full">
{/* Icon + Content Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<Icon className={cn('h-4 w-4', iconClass)} />
<div className="w-full group">
<div
className={cn(
'flex items-start gap-3 w-full rounded px-2 py-1 -mx-2 transition-colors',
hasExpandableContent && 'hover:bg-muted/50 cursor-pointer'
)}
onClick={handleToggle}
>
{/* Icon with hover-to-show chevron */}
<div className={cn(
'flex-shrink-0 mt-0.5 relative w-4 h-4',
hasExpandableContent && 'cursor-pointer'
)}>
<Icon className={cn(
'h-4 w-4 absolute inset-0 transition-opacity',
iconClass,
hasExpandableContent && 'group-hover:opacity-0'
)} />
{hasExpandableContent && (
isExpanded
? <IconChevronDown className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
: <IconChevronRight className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
)}
</div>
{/* Content */}
@@ -101,37 +124,19 @@ export function StatusMessage({ comment }: { comment: Message }) {
{message || 'An error occurred'}
</div>
{/* Expandable error details */}
{hasErrorDetails && errorDetails.length > 0 && (
<div className="mt-2">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="inline-flex items-center gap-1.5 text-left cursor-pointer hover:opacity-70 transition-opacity"
>
<span className="font-mono text-xs text-muted-foreground">
{isExpanded ? 'Hide details' : 'Show details'}
</span>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)}
</button>
{isExpanded && (
<div className="mt-2 pl-4 border-l-2 border-border/30 space-y-2">
{errorDetails.map((detail, index) => (
<div key={index}>
<div className="text-[10px] uppercase tracking-wide text-muted-foreground/60 mb-0.5">
{detail.label}
</div>
<pre className="text-xs bg-muted/30 rounded p-2 overflow-x-auto whitespace-pre-wrap break-all font-mono">
{detail.value}
</pre>
</div>
))}
{/* Expanded error details */}
{isExpanded && hasExpandableContent && (
<div className="mt-2 pl-4 border-l-2 border-border/30 space-y-2">
{errorDetails.map((detail) => (
<div key={detail.label}>
<div className="text-[10px] uppercase tracking-wide text-muted-foreground/60 mb-0.5">
{detail.label}
</div>
<pre className="text-xs bg-muted/30 rounded p-2 overflow-x-auto whitespace-pre-wrap break-all font-mono">
{detail.value}
</pre>
</div>
)}
))}
</div>
)}
@@ -154,4 +159,4 @@ export function StatusMessage({ comment }: { comment: Message }) {
</div>
</div>
);
}
});
@@ -1,11 +1,14 @@
'use client';
import { useState } from 'react';
import { IconBrain, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { useState, memo } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { IconBrain } from '@tabler/icons-react';
import type { Message } from '@/lib/types/http';
import type { RichMetadata } from '@/components/task/chat/types';
import { ExpandableRow } from './expandable-row';
export function ThinkingMessage({ comment }: { comment: Message }) {
export const ThinkingMessage = memo(function ThinkingMessage({ comment }: { comment: Message }) {
const [isExpanded, setIsExpanded] = useState(false);
const metadata = comment.metadata as RichMetadata | undefined;
const text = metadata?.thinking ?? comment.content;
@@ -13,41 +16,26 @@ export function ThinkingMessage({ comment }: { comment: Message }) {
if (!text) return null;
return (
<div className="w-full">
{/* Icon + Summary Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<IconBrain className="h-4 w-4 text-muted-foreground" />
<ExpandableRow
icon={<IconBrain className="h-4 w-4 text-muted-foreground" />}
header={
<div className="flex items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5">
<span className="font-mono text-xs text-muted-foreground">Thinking</span>
</span>
</div>
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => setIsExpanded(!isExpanded)}
className="inline-flex items-center gap-1.5 text-left cursor-pointer hover:opacity-70 transition-opacity"
>
<span className="font-mono text-xs text-muted-foreground">
Thinking
</span>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)}
</button>
</div>
{/* Expanded Content */}
{isExpanded && (
<div className="mt-2 pl-4 border-l-2 border-border/30">
<div className="whitespace-pre-wrap leading-normal text-xs text-foreground/80">{text}</div>
</div>
)}
}
hasExpandableContent={!!text}
isExpanded={isExpanded}
onToggle={() => setIsExpanded(!isExpanded)}
>
<div className="pl-4 border-l-2 border-border/30">
<div className="prose prose-sm prose-neutral dark:prose-invert max-w-none text-xs text-foreground/70 [&>*]:my-1 [&>p]:my-1 [&>ul]:my-1 [&>ol]:my-1 [&_strong]:text-foreground/80 [&_code]:text-foreground/70 [&_code]:bg-muted/50 [&_code]:px-1 [&_code]:py-0.5 [&_code]:rounded [&_code]:text-[0.9em]">
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{text}
</ReactMarkdown>
</div>
</div>
</div>
</ExpandableRow>
);
}
});
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useState, memo } from 'react';
import {
IconCheck,
IconChevronDown,
@@ -9,12 +9,12 @@ import {
IconEdit,
IconEye,
IconFile,
IconLoader2,
IconSearch,
IconTerminal2,
IconX,
} from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import { GridSpinner } from '@/components/grid-spinner';
import { cn, toRelativePath, transformPathsInText } from '@/lib/utils';
import { getWebSocketClient } from '@/lib/ws/connection';
import type { Message } from '@/lib/types/http';
import type { ToolCallMetadata } from '@/components/task/chat/types';
@@ -75,7 +75,7 @@ function getStatusIcon(status?: string, permissionStatus?: string) {
return <IconX className="h-3.5 w-3.5 text-red-500" />;
case 'running':
case 'in_progress':
return <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
return <GridSpinner className="text-muted-foreground" />;
default:
return null;
}
@@ -84,14 +84,16 @@ function getStatusIcon(status?: string, permissionStatus?: string) {
type ToolCallMessageProps = {
comment: Message;
permissionMessage?: Message;
worktreePath?: string;
};
export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageProps) {
export const ToolCallMessage = memo(function ToolCallMessage({ comment, permissionMessage, worktreePath }: ToolCallMessageProps) {
const metadata = comment.metadata as ToolCallMetadata | undefined;
const permissionMetadata = permissionMessage?.metadata as PermissionRequestMetadata | undefined;
const toolName = metadata?.tool_name ?? '';
const title = metadata?.title ?? comment.content ?? 'Tool call';
const rawTitle = metadata?.title ?? comment.content ?? 'Tool call';
const title = transformPathsInText(rawTitle, worktreePath);
const status = metadata?.status;
const args = metadata?.args;
const result = metadata?.result;
@@ -189,50 +191,60 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP
const isSuccess = status === 'complete' && !permissionStatus;
const handleToggleExpand = () => {
if (hasDetails) {
setIsExpanded(!isExpanded);
setIsManuallyToggled(true);
}
};
return (
<div className="w-full">
{/* Icon + Summary Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
{getToolIcon(toolName, cn(
'h-4 w-4',
isPermissionPending ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
))}
<div className="w-full group">
<div
className={cn(
'flex items-start gap-3 w-full rounded px-2 py-1 -mx-2 transition-colors',
hasDetails && 'hover:bg-muted/50 cursor-pointer'
)}
onClick={handleToggleExpand}
>
{/* Icon with hover-to-show chevron */}
<div className={cn(
'flex-shrink-0 mt-0.5 relative w-4 h-4',
hasDetails && 'cursor-pointer'
)}>
{/* Show tool icon by default, chevron on hover if expandable */}
<div className={cn(
'absolute inset-0 transition-opacity',
hasDetails && 'group-hover:opacity-0'
)}>
{getToolIcon(toolName, cn(
'h-4 w-4',
isPermissionPending ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
))}
</div>
{hasDetails && (
isExpanded
? <IconChevronDown className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
: <IconChevronRight className="h-4 w-4 text-muted-foreground absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity" />
)}
</div>
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => {
if (hasDetails) {
setIsExpanded(!isExpanded);
setIsManuallyToggled(true);
}
}}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasDetails && 'cursor-pointer hover:opacity-70 transition-opacity',
isPermissionPending && 'text-amber-600 dark:text-amber-400'
)}
disabled={!hasDetails}
>
<span className={cn(
'inline-flex items-center gap-1.5',
isPermissionPending && 'text-amber-600 dark:text-amber-400'
)}>
<span className="font-mono text-xs">
{title}
</span>
{/* Status indicator - only show if not success */}
{!isSuccess && getStatusIcon(status, permissionStatus)}
{hasDetails && (
isExpanded
? <IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
: <IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)}
</button>
</span>
{filePath && (
<span className="text-xs text-muted-foreground/60 truncate">
{filePath}
{toRelativePath(filePath, worktreePath)}
</span>
)}
</div>
@@ -282,4 +294,4 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP
</div>
</div>
);
}
});
@@ -1,12 +1,17 @@
'use client';
import { useState, useRef } from 'react';
import { IconCheck, IconX, IconLoader2, IconEdit, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { useState, useRef, memo, useCallback } from 'react';
import { IconCheck, IconX, IconEdit, IconFilePlus } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { transformPathsInText } from '@/lib/utils';
import { FilePathButton } from './file-path-button';
import type { Message } from '@/lib/types/http';
import { DiffViewBlock } from './diff-view-block';
import { ExpandableRow } from './expandable-row';
type FileMutation = {
type?: string;
content?: string;
old_content?: string;
new_content?: string;
diff?: string;
@@ -36,7 +41,13 @@ function parseDiffToHunks(diffString: string): string[] {
return hunks;
}
export function ToolEditMessage({ comment }: { comment: Message }) {
type ToolEditMessageProps = {
comment: Message;
worktreePath?: string;
onOpenFile?: (path: string) => void;
};
export const ToolEditMessage = memo(function ToolEditMessage({ comment, worktreePath, onOpenFile }: ToolEditMessageProps) {
const metadata = comment.metadata as ToolEditMetadata | undefined;
const [manualExpandState, setManualExpandState] = useState<boolean | null>(null);
const prevStatusRef = useRef(metadata?.status);
@@ -44,13 +55,20 @@ export function ToolEditMessage({ comment }: { comment: Message }) {
const status = metadata?.status;
const normalized = metadata?.normalized;
const filePath = normalized?.modify_file?.file_path;
const diffString = normalized?.modify_file?.mutations?.[0]?.diff;
const mutation = normalized?.modify_file?.mutations?.[0];
const diffString = mutation?.diff;
const writeContent = mutation?.content; // For Write tool (create operations)
const isWriteOperation = mutation?.type === 'create';
const diff = diffString ? {
hunks: parseDiffToHunks(diffString),
oldFile: { fileName: filePath },
newFile: { fileName: filePath },
} : undefined;
const hasExpandableContent = !!(diff || writeContent);
const isSuccess = status === 'complete';
const Icon = isWriteOperation ? IconFilePlus : IconEdit;
// Reset manual state when status changes (allows auto-expand behavior to resume)
if (prevStatusRef.current !== status) {
@@ -61,7 +79,12 @@ export function ToolEditMessage({ comment }: { comment: Message }) {
}
// Derive expanded state: manual override takes precedence, otherwise auto-expand when running
const isExpanded = manualExpandState ?? (status === 'running');
const autoExpanded = status === 'running';
const isExpanded = manualExpandState ?? autoExpanded;
const handleToggle = useCallback(() => {
setManualExpandState((prev) => !(prev ?? autoExpanded));
}, [autoExpanded]);
const getStatusIcon = () => {
switch (status) {
@@ -70,44 +93,54 @@ export function ToolEditMessage({ comment }: { comment: Message }) {
case 'error':
return <IconX className="h-3.5 w-3.5 text-red-500" />;
case 'running':
return <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
return <GridSpinner className="text-muted-foreground" />;
default:
return null;
}
};
// Count lines for Write content
const lineCount = writeContent ? writeContent.split('\n').length : 0;
const getSummary = () => {
if (isWriteOperation && lineCount > 0) {
return `Write ${lineCount} line${lineCount !== 1 ? 's' : ''}`;
}
return transformPathsInText(comment.content, worktreePath);
};
return (
<div className="w-full">
<div className="flex items-start gap-3 w-full">
<div className="flex-shrink-0 mt-0.5">
<IconEdit className="h-4 w-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => {
setManualExpandState(!isExpanded);
}}
className="inline-flex items-center gap-1.5 text-left cursor-pointer hover:opacity-70 transition-opacity"
>
<span className="font-mono text-xs">{comment.content}</span>
{!isSuccess && getStatusIcon()}
{diff && (isExpanded ? <IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50" /> : <IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50" />)}
</button>
{filePath && (
<span className="text-xs text-muted-foreground/60 truncate">{filePath}</span>
)}
</div>
{isExpanded && diff && (
<div className="mt-2">
<DiffViewBlock diff={diff} showTitle={false} className="mt-0 border-0 px-0" />
</div>
<ExpandableRow
icon={<Icon className="h-4 w-4 text-muted-foreground" />}
header={
<div className="flex items-center gap-2 text-xs min-w-0">
<span className="inline-flex items-center gap-1.5 shrink-0 whitespace-nowrap">
<span className="font-mono text-xs text-muted-foreground">{getSummary()}</span>
{!isSuccess && getStatusIcon()}
</span>
{filePath && (
<span className="min-w-0 flex-1">
<FilePathButton
filePath={filePath}
worktreePath={worktreePath}
onOpenFile={onOpenFile}
/>
</span>
)}
</div>
</div>
</div>
}
hasExpandableContent={hasExpandableContent}
isExpanded={isExpanded}
onToggle={handleToggle}
>
{diff ? (
<DiffViewBlock diff={diff} showTitle={false} className="mt-0 border-0 px-0" />
) : writeContent ? (
<div className="pl-4 border-l-2 border-border/30">
<pre className="text-xs bg-muted/30 rounded p-2 overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap">
{writeContent}
</pre>
</div>
) : null}
</ExpandableRow>
);
}
});
@@ -1,9 +1,11 @@
'use client';
import { useState, useRef } from 'react';
import { IconCheck, IconX, IconLoader2, IconTerminal, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import { useState, useRef, memo, useCallback } from 'react';
import { IconCheck, IconX, IconTerminal } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { transformPathsInText } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import { ExpandableRow } from './expandable-row';
type ShellExecOutput = {
exit_code?: number;
@@ -31,14 +33,22 @@ type ToolExecuteMetadata = {
normalized?: NormalizedPayload;
};
export function ToolExecuteMessage({ comment }: { comment: Message }) {
type ToolExecuteMessageProps = {
comment: Message;
worktreePath?: string;
};
export const ToolExecuteMessage = memo(function ToolExecuteMessage({ comment, worktreePath }: ToolExecuteMessageProps) {
const metadata = comment.metadata as ToolExecuteMetadata | undefined;
const [manualExpandState, setManualExpandState] = useState<boolean | null>(null);
const prevStatusRef = useRef(metadata?.status);
const status = metadata?.status;
const output = metadata?.normalized?.shell_exec?.output;
const shellExec = metadata?.normalized?.shell_exec;
const output = shellExec?.output;
const workDir = shellExec?.work_dir;
const hasOutput = output?.stdout || output?.stderr;
const hasExpandableContent = hasOutput || workDir;
const isSuccess = status === 'complete' && (output?.exit_code === 0 || output?.exit_code === undefined);
// Reset manual state when status changes (allows auto-expand behavior to resume)
@@ -50,7 +60,12 @@ export function ToolExecuteMessage({ comment }: { comment: Message }) {
}
// Derive expanded state: manual override takes precedence, otherwise auto-expand when running
const isExpanded = manualExpandState ?? (status === 'running');
const autoExpanded = status === 'running';
const isExpanded = manualExpandState ?? autoExpanded;
const handleToggle = useCallback(() => {
setManualExpandState((prev) => !(prev ?? autoExpanded));
}, [autoExpanded]);
const getStatusIcon = () => {
switch (status) {
@@ -59,56 +74,49 @@ export function ToolExecuteMessage({ comment }: { comment: Message }) {
case 'error':
return <IconX className="h-3.5 w-3.5 text-red-500" />;
case 'running':
return <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
return <GridSpinner className="text-muted-foreground" />;
default:
return null;
}
};
// Format work_dir for display (make relative if possible)
const displayWorkDir = workDir ? transformPathsInText(workDir, worktreePath) : null;
return (
<div className="w-full">
<div className="flex items-start gap-3 w-full">
<div className="flex-shrink-0 mt-0.5">
<IconTerminal className="h-4 w-4 text-muted-foreground" />
<ExpandableRow
icon={<IconTerminal className="h-4 w-4 text-muted-foreground" />}
header={
<div className="flex items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5">
<span className="font-mono text-xs text-muted-foreground">{transformPathsInText(comment.content, worktreePath)}</span>
{!isSuccess && getStatusIcon()}
</span>
</div>
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => {
if (hasOutput) {
setManualExpandState(!isExpanded);
}
}}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasOutput && 'cursor-pointer hover:opacity-70 transition-opacity'
)}
disabled={!hasOutput}
>
<span className="font-mono text-xs">{comment.content}</span>
{!isSuccess && getStatusIcon()}
{hasOutput && (isExpanded ? <IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50" /> : <IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50" />)}
</button>
}
hasExpandableContent={!!hasExpandableContent}
isExpanded={isExpanded}
onToggle={handleToggle}
>
<div className="pl-4 border-l-2 border-border/30 space-y-2">
{/* Only show cwd when there's no output */}
{displayWorkDir && !hasOutput && (
<div className="text-xs text-muted-foreground">
<span className="opacity-60">cwd:</span>{' '}
<span className="font-mono" title={workDir}>{displayWorkDir}</span>
</div>
{isExpanded && hasOutput && (
<div className="mt-2 pl-4 border-l-2 border-border/30">
{output?.stdout && (
<pre className="text-xs bg-muted/30 rounded p-2 overflow-x-auto whitespace-pre-wrap">
{output.stdout}
</pre>
)}
{output?.stderr && (
<pre className="mt-2 text-xs bg-red-500/10 text-red-600 dark:text-red-400 rounded p-2 overflow-x-auto whitespace-pre-wrap">
{output.stderr}
</pre>
)}
</div>
)}
</div>
)}
{output?.stdout && (
<pre className="text-xs bg-muted/30 rounded p-2 overflow-x-auto whitespace-pre-wrap max-h-[200px]">
{output.stdout}
</pre>
)}
{output?.stderr && (
<pre className="text-xs bg-red-500/10 text-red-600 dark:text-red-400 rounded max-h-[200px] p-2 overflow-x-auto whitespace-pre-wrap">
{output.stderr}
</pre>
)}
</div>
</div>
</ExpandableRow>
);
}
});
@@ -1,25 +1,29 @@
'use client';
import { IconCheck, IconX, IconLoader2, IconEye, IconSearch } from '@tabler/icons-react';
import { useState, useRef, memo, useCallback } from 'react';
import { IconCheck, IconX, IconFileCode2 } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { FilePathButton } from './file-path-button';
import type { Message } from '@/lib/types/http';
import { ExpandableRow } from './expandable-row';
type ReadFileOutput = {
content?: string;
line_count?: number;
truncated?: boolean;
language?: string;
};
type ReadFilePayload = {
file_path?: string;
offset?: number;
limit?: number;
};
type CodeSearchPayload = {
query?: string;
pattern?: string;
path?: string;
glob?: string;
output?: ReadFileOutput;
};
type NormalizedPayload = {
kind?: string;
read_file?: ReadFilePayload;
code_search?: CodeSearchPayload;
};
type ToolReadMetadata = {
@@ -28,20 +32,42 @@ type ToolReadMetadata = {
normalized?: NormalizedPayload;
};
export function ToolReadMessage({ comment }: { comment: Message }) {
type ToolReadMessageProps = {
comment: Message;
worktreePath?: string;
sessionId?: string;
onOpenFile?: (path: string) => void;
};
export const ToolReadMessage = memo(function ToolReadMessage({ comment, worktreePath, onOpenFile }: ToolReadMessageProps) {
const metadata = comment.metadata as ToolReadMetadata | undefined;
const [manualExpandState, setManualExpandState] = useState<boolean | null>(null);
const prevStatusRef = useRef(metadata?.status);
const status = metadata?.status;
const normalized = metadata?.normalized;
const kind = normalized?.kind;
// Determine display based on kind
const isCodeSearch = kind === 'code_search';
const filePath = normalized?.read_file?.file_path;
const searchPath = normalized?.code_search?.path;
const searchPattern = normalized?.code_search?.glob || normalized?.code_search?.pattern;
const readFile = normalized?.read_file;
const readOutput = readFile?.output;
const filePath = readFile?.file_path;
const hasOutput = !!readOutput?.content;
const isSuccess = status === 'complete';
const Icon = isCodeSearch ? IconSearch : IconEye;
// Reset manual state when status changes (allows auto-expand behavior to resume)
if (prevStatusRef.current !== status) {
prevStatusRef.current = status;
if (manualExpandState !== null) {
setManualExpandState(null);
}
}
// Derive expanded state: manual override takes precedence, otherwise auto-expand when running
const autoExpanded = status === 'running';
const isExpanded = manualExpandState ?? autoExpanded;
const handleToggle = useCallback(() => {
setManualExpandState((prev) => !(prev ?? autoExpanded));
}, [autoExpanded]);
const getStatusIcon = () => {
switch (status) {
@@ -50,36 +76,54 @@ export function ToolReadMessage({ comment }: { comment: Message }) {
case 'error':
return <IconX className="h-3.5 w-3.5 text-red-500" />;
case 'running':
return <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
return <GridSpinner className="text-muted-foreground" />;
default:
return null;
}
};
// Display path - either file path for read or search path for code search
const displayPath = isCodeSearch ? searchPath : filePath;
const displayPattern = isCodeSearch ? searchPattern : null;
// Generate summary text
const getSummary = () => {
if (readOutput?.line_count) {
return `Read ${readOutput.line_count} line${readOutput.line_count !== 1 ? 's' : ''}`;
}
return 'Read';
};
return (
<div className="w-full">
<div className="flex items-start gap-3 w-full">
<div className="flex-shrink-0 mt-0.5">
<Icon className="h-4 w-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<span className="font-mono text-xs">{comment.content}</span>
<ExpandableRow
icon={<IconFileCode2 className="h-4 w-4 text-muted-foreground" />}
header={
<div className="flex items-center gap-2 text-xs min-w-0">
<span className="inline-flex items-center gap-1.5 shrink-0 whitespace-nowrap">
<span className="font-mono text-xs text-muted-foreground">{getSummary()}</span>
{!isSuccess && getStatusIcon()}
{displayPattern && (
<span className="text-xs text-muted-foreground/60 font-mono truncate">{displayPattern}</span>
)}
{displayPath && (
<span className="text-xs text-muted-foreground/60 truncate">{displayPath}</span>
)}
</div>
</span>
{filePath && (
<span className="min-w-0">
<FilePathButton
filePath={filePath}
worktreePath={worktreePath}
onOpenFile={onOpenFile}
/>
</span>
)}
{readOutput?.truncated && (
<span className="text-xs text-amber-500/80 shrink-0">(truncated)</span>
)}
</div>
</div>
</div>
}
hasExpandableContent={hasOutput}
isExpanded={isExpanded}
onToggle={handleToggle}
>
{readOutput?.content && (
<div className="relative rounded-md border border-border/50 overflow-hidden bg-muted/20">
<pre className="text-xs p-3 overflow-x-auto max-h-[200px] overflow-y-auto">
<code>{readOutput.content}</code>
</pre>
</div>
)}
</ExpandableRow>
);
}
});
@@ -0,0 +1,138 @@
'use client';
import { useState, useRef, memo, useCallback } from 'react';
import { IconCheck, IconX, IconSearch } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { toRelativePath } from '@/lib/utils';
import { FilePathButton } from './file-path-button';
import type { Message } from '@/lib/types/http';
import { ExpandableRow } from './expandable-row';
type CodeSearchOutput = {
files?: string[];
file_count?: number;
truncated?: boolean;
};
type CodeSearchPayload = {
query?: string;
pattern?: string;
path?: string;
glob?: string;
output?: CodeSearchOutput;
};
type NormalizedPayload = {
kind?: string;
code_search?: CodeSearchPayload;
};
type ToolSearchMetadata = {
tool_call_id?: string;
status?: 'pending' | 'running' | 'complete' | 'error';
normalized?: NormalizedPayload;
};
type ToolSearchMessageProps = {
comment: Message;
worktreePath?: string;
onOpenFile?: (path: string) => void;
};
export const ToolSearchMessage = memo(function ToolSearchMessage({ comment, worktreePath, onOpenFile }: ToolSearchMessageProps) {
const metadata = comment.metadata as ToolSearchMetadata | undefined;
const [manualExpandState, setManualExpandState] = useState<boolean | null>(null);
const prevStatusRef = useRef(metadata?.status);
const status = metadata?.status;
const normalized = metadata?.normalized;
const codeSearch = normalized?.code_search;
const searchOutput = codeSearch?.output;
const searchPath = codeSearch?.path;
const searchPattern = codeSearch?.glob || codeSearch?.pattern || codeSearch?.query;
const hasOutput = !!(searchOutput?.files && searchOutput.files.length > 0);
const isSuccess = status === 'complete';
// Reset manual state when status changes (allows auto-expand behavior to resume)
if (prevStatusRef.current !== status) {
prevStatusRef.current = status;
if (manualExpandState !== null) {
setManualExpandState(null);
}
}
// Derive expanded state: manual override takes precedence, otherwise auto-expand when running
const autoExpanded = status === 'running';
const isExpanded = manualExpandState ?? autoExpanded;
const handleToggle = useCallback(() => {
setManualExpandState((prev) => !(prev ?? autoExpanded));
}, [autoExpanded]);
const getStatusIcon = () => {
switch (status) {
case 'complete':
return <IconCheck className="h-3.5 w-3.5 text-green-500" />;
case 'error':
return <IconX className="h-3.5 w-3.5 text-red-500" />;
case 'running':
return <GridSpinner className="text-muted-foreground" />;
default:
return null;
}
};
// Generate summary text
const getSummary = () => {
if (searchOutput?.files && searchOutput.files.length > 0) {
const count = searchOutput.file_count || searchOutput.files.length;
return `Found ${count} file${count !== 1 ? 's' : ''}`;
}
return 'Searching';
};
return (
<ExpandableRow
icon={<IconSearch className="h-4 w-4 text-muted-foreground" />}
header={
<div className="flex items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5">
<span className="font-mono text-xs text-muted-foreground">{getSummary()}</span>
{!isSuccess && getStatusIcon()}
</span>
{searchPattern && (
<span className="text-xs text-muted-foreground/60 font-mono">{searchPattern}</span>
)}
{searchPath && (
<span className="text-xs text-muted-foreground/60 truncate font-mono bg-muted/30 px-1.5 py-0.5 rounded">
{toRelativePath(searchPath, worktreePath)}
</span>
)}
</div>
}
hasExpandableContent={hasOutput}
isExpanded={isExpanded}
onToggle={handleToggle}
>
{searchOutput?.files && (
<div className="rounded-md border border-border/50 overflow-hidden bg-muted/20">
<div className="text-xs space-y-0.5 max-h-[200px] overflow-y-auto p-1">
{searchOutput.files.map((file) => (
<FilePathButton
key={file}
filePath={file}
worktreePath={worktreePath}
onOpenFile={onOpenFile}
variant="list-item"
/>
))}
{searchOutput.truncated && (
<div className="text-amber-500/80 mt-1 px-2">...and more files (truncated)</div>
)}
</div>
</div>
)}
</ExpandableRow>
);
});
@@ -0,0 +1,111 @@
'use client';
import { useState, useCallback, memo } from 'react';
import { IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { cn } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import type { ToolCallMetadata } from '@/components/task/chat/types';
type ToolSubagentMessageProps = {
comment: Message;
childMessages: Message[];
worktreePath?: string;
onOpenFile?: (path: string) => void;
renderChild: (message: Message) => React.ReactNode;
};
// Custom comparison function that ignores renderChild (it's always recreated but referentially stable in behavior)
function arePropsEqual(
prevProps: ToolSubagentMessageProps,
nextProps: ToolSubagentMessageProps
): boolean {
return (
prevProps.comment === nextProps.comment &&
prevProps.childMessages === nextProps.childMessages &&
prevProps.worktreePath === nextProps.worktreePath &&
prevProps.onOpenFile === nextProps.onOpenFile
);
}
export const ToolSubagentMessage = memo(function ToolSubagentMessage({
comment,
childMessages,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
worktreePath,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onOpenFile,
renderChild,
}: ToolSubagentMessageProps) {
const metadata = comment.metadata as ToolCallMetadata | undefined;
const status = metadata?.status;
const normalized = metadata?.normalized;
const subagentTask = normalized?.subagent_task;
const description = subagentTask?.description || comment.content || 'Subagent';
const subagentType = subagentTask?.subagent_type || 'Task';
const childCount = childMessages.length;
const isActive = status === 'running';
// Track manual override state - null means "use auto behavior"
const [manualExpandState, setManualExpandState] = useState<boolean | null>(null);
// Auto behavior: expand if active, collapse otherwise
const autoExpanded = isActive;
// Derive expanded state: manual override takes precedence, otherwise use auto
const isExpanded = manualExpandState ?? autoExpanded;
const handleToggle = useCallback(() => {
setManualExpandState((prev) => !(prev ?? autoExpanded));
}, [autoExpanded]);
return (
<div className="w-full">
{/* Header */}
<button
type="button"
onClick={handleToggle}
className={cn(
'flex items-center gap-2 w-full text-left px-2 py-1.5 -mx-2 rounded',
'hover:bg-muted/30 transition-colors cursor-pointer'
)}
>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/60 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/60 flex-shrink-0" />
)}
<span className="bg-muted text-muted-foreground text-[10px] px-1.5 rounded font-medium uppercase tracking-wide">
{subagentType}
</span>
<span className="font-mono text-xs truncate text-muted-foreground inline-flex items-center gap-1.5">
{description}
{isActive && <GridSpinner className="text-muted-foreground shrink-0" />}
</span>
{childCount > 0 && (
<span className="text-muted-foreground/60 text-xs px-1.5 rounded min-w-[20px] text-center font-mono">
{childCount} tool call{childCount !== 1 ? 's' : ''}
</span>
)}
</button>
{/* Expanded content */}
{isExpanded && childMessages.length > 0 && (
<div className="ml-2 pl-4 border-l-2 border-border/30 mt-1 space-y-2">
{childMessages.map((child) => (
<div key={child.id}>{renderChild(child)}</div>
))}
</div>
)}
{/* Expanded but no children yet */}
{isExpanded && childMessages.length === 0 && isActive && (
<div className="ml-2 pl-4 border-l-2 border-border/30 mt-1">
<span className="text-xs text-muted-foreground italic">Subagent working...</span>
</div>
)}
</div>
);
}, arePropsEqual);
@@ -0,0 +1,196 @@
'use client';
import { useState, useCallback, memo } from 'react';
import { IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { cn, transformPathsInText } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import type { TurnGroup } from '@/hooks/use-processed-messages';
import type { ToolCallMetadata } from '@/components/task/chat/types';
import { MessageRenderer } from '@/components/task/chat/message-renderer';
type TurnGroupMessageProps = {
group: TurnGroup;
sessionId: string | null;
permissionsByToolCallId: Map<string, Message>;
childrenByParentToolCallId?: Map<string, Message[]>;
taskId?: string;
worktreePath?: string;
onOpenFile?: (path: string) => void;
/** Whether this is the last turn group in the current turn */
isLastGroup?: boolean;
/** Whether the turn is still active (agent is running) */
isTurnActive?: boolean;
};
function countMessageTypes(messages: Message[]): { toolCalls: number; subagents: number } {
let toolCalls = 0;
let subagents = 0;
for (const msg of messages) {
const metadata = msg.metadata as ToolCallMetadata | undefined;
if (metadata?.normalized?.kind === 'subagent_task') {
subagents++;
} else {
toolCalls++;
}
}
return { toolCalls, subagents };
}
function getGroupDescription(messages: Message[], isActive: boolean): string {
// When active, get the last message's title or content for the description
if (isActive) {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
const metadata = msg.metadata as ToolCallMetadata | undefined;
if (metadata?.title) {
return metadata.title;
}
if (msg.content && msg.content.length > 0) {
// Truncate long content
return msg.content.slice(0, 60) + (msg.content.length > 60 ? '...' : '');
}
}
return 'Working...';
}
// When complete, show counts with subagent breakdown
const { toolCalls, subagents } = countMessageTypes(messages);
if (subagents === 0) {
return `tool call${toolCalls !== 1 ? 's' : ''}`;
}
if (toolCalls === 0) {
return `subagent${subagents !== 1 ? 's' : ''}`;
}
return `tool call${toolCalls !== 1 ? 's' : ''}, ${subagents} subagent${subagents !== 1 ? 's' : ''}`;
}
function hasPendingPermission(
messages: Message[],
permissionsByToolCallId: Map<string, Message>
): boolean {
for (const msg of messages) {
if (msg.type === 'tool_call') {
const toolCallId = (msg.metadata as { tool_call_id?: string } | undefined)?.tool_call_id;
if (toolCallId) {
const permissionMsg = permissionsByToolCallId.get(toolCallId);
if (permissionMsg) {
const permStatus = (permissionMsg.metadata as { status?: string } | undefined)?.status;
if (permStatus !== 'approved' && permStatus !== 'rejected') {
return true;
}
}
}
}
}
return false;
}
// Tool message types that have status tracking
const TOOL_MESSAGE_TYPES = new Set(['tool_call', 'tool_edit', 'tool_read', 'tool_execute', 'tool_search']);
/**
* Check if any tool or subagent in the group is still running.
* A tool/subagent is considered running if it's not in a terminal state (complete or error).
*/
function hasRunningTool(messages: Message[]): boolean {
for (const msg of messages) {
const metadata = msg.metadata as ToolCallMetadata | undefined;
// Check tool messages and subagent tasks
const isToolMessage = msg.type && TOOL_MESSAGE_TYPES.has(msg.type);
const isSubagent = metadata?.normalized?.kind === 'subagent_task';
if (!isToolMessage && !isSubagent) continue;
const status = metadata?.status;
// A tool/subagent is running if it's not in a terminal state
if (status !== 'complete' && status !== 'error') {
return true;
}
}
return false;
}
export const TurnGroupMessage = memo(function TurnGroupMessage({
group,
sessionId,
permissionsByToolCallId,
childrenByParentToolCallId,
taskId,
worktreePath,
onOpenFile,
isLastGroup = false,
isTurnActive = false,
}: TurnGroupMessageProps) {
// Check if any tool in the group is still running
const isGroupRunning = hasRunningTool(group.messages);
// Check if any tool has pending permission
const hasPending = hasPendingPermission(group.messages, permissionsByToolCallId);
// Track manual override state - null means "use auto behavior"
const [manualExpandState, setManualExpandState] = useState<boolean | null>(null);
// Auto behavior: expand if running, has pending, or is the last group while turn is active
const autoExpanded = isGroupRunning || hasPending || (isTurnActive && isLastGroup);
// Derive expanded state: manual override takes precedence, otherwise use auto
const isExpanded = manualExpandState ?? autoExpanded;
const handleToggle = useCallback(() => {
setManualExpandState((prev) => !(prev ?? autoExpanded));
}, [autoExpanded]);
const rawDescription = getGroupDescription(group.messages, isGroupRunning);
const description = transformPathsInText(rawDescription, worktreePath);
const count = group.messages.length;
return (
<div className="w-full">
{/* Header */}
<button
type="button"
onClick={handleToggle}
className={cn(
'flex items-center gap-2 w-full text-left px-2 py-1.5 -mx-2 rounded',
'hover:bg-muted/30 transition-colors cursor-pointer'
)}
>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/60 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/60 flex-shrink-0" />
)}
<span className="bg-muted text-muted-foreground text-xs px-1.5 rounded min-w-[20px] text-center font-mono">
{count}
</span>
<span className="font-mono text-xs truncate text-muted-foreground inline-flex items-center gap-1.5">
{description}
{isGroupRunning && <GridSpinner className="text-muted-foreground shrink-0" />}
</span>
</button>
{/* Expanded content */}
{isExpanded && (
<div className="ml-2 pl-4 border-l-2 border-border/30 mt-1 space-y-2">
{group.messages.map((msg) => (
<MessageRenderer
key={msg.id}
comment={msg}
isTaskDescription={false}
taskId={taskId}
permissionsByToolCallId={permissionsByToolCallId}
childrenByParentToolCallId={childrenByParentToolCallId}
worktreePath={worktreePath}
sessionId={sessionId ?? undefined}
onOpenFile={onOpenFile}
/>
))}
</div>
)}
</div>
);
});
@@ -1,5 +1,6 @@
'use client';
import { memo } from 'react';
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { cn } from '@/lib/utils';
import { useSessionContextWindow } from '@/hooks/domains/session/use-session-context-window';
@@ -26,7 +27,7 @@ function getCircleColor(efficiency: number): string {
return 'text-blue-300';
}
export function TokenUsageDisplay({ sessionId, className }: TokenUsageDisplayProps) {
export const TokenUsageDisplay = memo(function TokenUsageDisplay({ sessionId, className }: TokenUsageDisplayProps) {
const contextWindow = useSessionContextWindow(sessionId);
if (!contextWindow || contextWindow.size === 0) return null;
@@ -89,5 +90,5 @@ export function TokenUsageDisplay({ sessionId, className }: TokenUsageDisplayPro
</TooltipContent>
</Tooltip>
);
}
});
+61
View File
@@ -12,14 +12,75 @@ export type GenericPayload = {
output?: unknown;
};
export type ReadFileOutput = {
content?: string;
line_count?: number;
truncated?: boolean;
language?: string;
};
export type ReadFilePayload = {
file_path?: string;
offset?: number;
limit?: number;
output?: ReadFileOutput;
};
export type CodeSearchOutput = {
files?: string[];
file_count?: number;
truncated?: boolean;
};
export type CodeSearchPayload = {
query?: string;
pattern?: string;
path?: string;
glob?: string;
output?: CodeSearchOutput;
};
export type FileMutation = {
type?: string;
content?: string;
old_content?: string;
new_content?: string;
diff?: string;
};
export type ModifyFilePayload = {
file_path?: string;
mutations?: FileMutation[];
};
export type ShellExecOutput = {
exit_code?: number;
stdout?: string;
stderr?: string;
};
export type ShellExecPayload = {
command?: string;
work_dir?: string;
description?: string;
timeout?: number;
background?: boolean;
output?: ShellExecOutput;
};
export type NormalizedPayload = {
kind?: string;
subagent_task?: SubagentTaskPayload;
generic?: GenericPayload;
read_file?: ReadFilePayload;
code_search?: CodeSearchPayload;
modify_file?: ModifyFilePayload;
shell_exec?: ShellExecPayload;
};
export type ToolCallMetadata = {
tool_call_id?: string;
parent_tool_call_id?: string; // For subagent nesting
tool_name?: string;
title?: string;
status?: 'pending' | 'running' | 'complete' | 'error';
@@ -1,32 +1,42 @@
'use client';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useCallback, useEffect, useMemo, useRef, memo } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { IconLoader2 } from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { SessionPanelContent } from '@kandev/ui/pannel-session';
import type { Message, TaskSessionState } from '@/lib/types/http';
import type { RenderItem } from '@/hooks/use-processed-messages';
import { MessageRenderer } from '@/components/task/chat/message-renderer';
import { TurnGroupMessage } from '@/components/task/chat/messages/turn-group-message';
import { AgentStatus } from '@/components/task/chat/messages/agent-status';
import { useLazyLoadMessages } from '@/hooks/use-lazy-load-messages';
type VirtualizedMessageListProps = {
items: RenderItem[];
messages: Message[];
permissionsByToolCallId: Map<string, Message>;
childrenByParentToolCallId: Map<string, Message[]>;
taskId?: string;
sessionId: string | null;
messagesLoading: boolean;
isWorking: boolean;
sessionState?: TaskSessionState;
worktreePath?: string;
onOpenFile?: (path: string) => void;
};
export function VirtualizedMessageList({
export const VirtualizedMessageList = memo(function VirtualizedMessageList({
items,
messages,
permissionsByToolCallId,
childrenByParentToolCallId,
taskId,
sessionId,
messagesLoading,
isWorking,
sessionState,
worktreePath,
onOpenFile,
}: VirtualizedMessageListProps) {
const messagesContainerRef = useRef<HTMLDivElement>(null);
const wasAtBottomRef = useRef(true);
@@ -35,7 +45,7 @@ export function VirtualizedMessageList({
const showLoadingState = (messagesLoading || isInitialLoading) && !isWorking;
const { loadMore, hasMore, isLoading: isLoadingMore } = useLazyLoadMessages(sessionId);
const itemCount = messages.length;
const itemCount = items.length;
// eslint-disable-next-line react-hooks/incompatible-library
const virtualizer = useVirtualizer({
@@ -45,26 +55,51 @@ export function VirtualizedMessageList({
overscan: 6,
});
const checkAtBottom = useCallback(() => {
// Use ref to track loading state to avoid recreating the scroll handler
const loadingRef = useRef({ hasMore, isLoadingMore });
loadingRef.current = { hasMore, isLoadingMore };
// Combined scroll handler: check if at bottom AND trigger lazy loading at top
const handleScroll = useCallback(() => {
const element = messagesContainerRef.current;
if (!element) return;
const { scrollTop, scrollHeight, clientHeight } = element;
// Track if we're at the bottom for auto-scroll behavior
wasAtBottomRef.current = scrollHeight - scrollTop - clientHeight < 48;
}, []);
// Trigger lazy load when scrolled near top
if (scrollTop < 40 && loadingRef.current.hasMore && !loadingRef.current.isLoadingMore) {
const prevScrollHeight = scrollHeight;
const prevScrollTop = scrollTop;
loadMore().then((added) => {
if (!added) return;
requestAnimationFrame(() => {
const nextScrollHeight = element.scrollHeight;
element.scrollTop = prevScrollTop + (nextScrollHeight - prevScrollHeight);
});
});
}
}, [loadMore]);
useEffect(() => {
const element = messagesContainerRef.current;
if (!element) return;
element.addEventListener('scroll', checkAtBottom);
return () => element.removeEventListener('scroll', checkAtBottom);
}, [checkAtBottom]);
element.addEventListener('scroll', handleScroll);
return () => element.removeEventListener('scroll', handleScroll);
}, [handleScroll]);
// Track last message content to detect streaming updates
const lastMessageContent = useMemo(() => {
if (messages.length === 0) return '';
const lastMsg = messages[messages.length - 1];
return lastMsg?.content ?? '';
}, [messages]);
if (items.length === 0) return '';
const lastItem = items[items.length - 1];
if (lastItem.type === 'turn_group') {
const lastMsg = lastItem.messages[lastItem.messages.length - 1];
return lastMsg?.content ?? '';
}
return lastItem.message?.content ?? '';
}, [items]);
// Scroll to bottom when new messages arrive or when last message content changes (streaming)
useEffect(() => {
@@ -76,6 +111,17 @@ export function VirtualizedMessageList({
// Scroll to bottom when agent starts running (running indicator appears)
const isRunning = sessionState === 'CREATED' || sessionState === 'STARTING' || sessionState === 'RUNNING';
// Find the last turn_group ID to keep it expanded while turn is active
const lastTurnGroupId = useMemo(() => {
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
if (item.type === 'turn_group') {
return item.id;
}
}
return null;
}, [items]);
useEffect(() => {
if (!isRunning) return;
const element = messagesContainerRef.current;
@@ -86,31 +132,6 @@ export function VirtualizedMessageList({
});
}, [isRunning]);
const virtualItems = virtualizer.getVirtualItems();
// Lazy load older messages when scrolling to top
useEffect(() => {
const [firstItem] = virtualItems;
if (!firstItem) return;
const element = messagesContainerRef.current;
if (!element) return;
if (firstItem.index !== 0 || element.scrollTop > 40) {
return;
}
if (!hasMore || isLoadingMore) {
return;
}
const prevScrollHeight = element.scrollHeight;
const prevScrollTop = element.scrollTop;
loadMore().then((added) => {
if (!added) return;
requestAnimationFrame(() => {
const nextScrollHeight = element.scrollHeight;
element.scrollTop = prevScrollTop + (nextScrollHeight - prevScrollHeight);
});
});
}, [virtualItems, hasMore, isLoadingMore, loadMore]);
return (
<SessionPanelContent
ref={messagesContainerRef}
@@ -125,7 +146,7 @@ export function VirtualizedMessageList({
{/* Show loading messages spinner when initially loading */}
{showLoadingState && (
<div className="flex items-center justify-center py-8 text-muted-foreground">
<IconLoader2 className="h-5 w-5 animate-spin mr-2" />
<GridSpinner className="text-primary mr-2" />
<span>Loading messages...</span>
</div>
)}
@@ -139,7 +160,8 @@ export function VirtualizedMessageList({
{!isInitialLoading && itemCount > 0 && (
<div className="relative w-full" style={{ height: `${virtualizer.getTotalSize()}px` }}>
{virtualizer.getVirtualItems().map((virtualRow) => {
const message = messages[virtualRow.index];
const item = items[virtualRow.index];
return (
<div
key={virtualRow.key}
@@ -149,12 +171,30 @@ export function VirtualizedMessageList({
style={{ transform: `translateY(${virtualRow.start}px)` }}
>
<div className="pb-2">
<MessageRenderer
comment={message}
isTaskDescription={message.id === 'task-description'}
taskId={taskId}
permissionsByToolCallId={permissionsByToolCallId}
/>
{item.type === 'turn_group' ? (
<TurnGroupMessage
group={item}
sessionId={sessionId}
permissionsByToolCallId={permissionsByToolCallId}
childrenByParentToolCallId={childrenByParentToolCallId}
taskId={taskId}
worktreePath={worktreePath}
onOpenFile={onOpenFile}
isLastGroup={item.id === lastTurnGroupId}
isTurnActive={isRunning}
/>
) : (
<MessageRenderer
comment={item.message}
isTaskDescription={item.message.id === 'task-description'}
taskId={taskId}
permissionsByToolCallId={permissionsByToolCallId}
childrenByParentToolCallId={childrenByParentToolCallId}
worktreePath={worktreePath}
sessionId={sessionId ?? undefined}
onOpenFile={onOpenFile}
/>
)}
</div>
</div>
);
@@ -169,4 +209,4 @@ export function VirtualizedMessageList({
/>
</SessionPanelContent>
);
}
});
@@ -1,78 +1,18 @@
'use client';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import { go } from '@codemirror/lang-go';
import { rust } from '@codemirror/lang-rust';
import { java } from '@codemirror/lang-java';
import { cpp } from '@codemirror/lang-cpp';
import { css } from '@codemirror/lang-css';
import { html } from '@codemirror/lang-html';
import { json } from '@codemirror/lang-json';
import { markdown } from '@codemirror/lang-markdown';
import { yaml } from '@codemirror/lang-yaml';
import { vscodeDark } from '@uiw/codemirror-theme-vscode';
import { EditorView } from '@codemirror/view';
import type { Extension } from '@codemirror/state';
import { getCodeMirrorExtensionFromPath } from '@/lib/languages';
type FileViewerContentProps = {
path: string;
content: string;
};
const getLanguageExtension = (path: string): Extension | undefined => {
const ext = path.split('.').pop()?.toLowerCase();
switch (ext) {
case 'js':
case 'mjs':
case 'cjs':
return javascript();
case 'jsx':
return javascript({ jsx: true });
case 'ts':
case 'mts':
case 'cts':
return javascript({ typescript: true });
case 'tsx':
return javascript({ jsx: true, typescript: true });
case 'py':
return python();
case 'go':
return go();
case 'rs':
return rust();
case 'java':
return java();
case 'cpp':
case 'cc':
case 'cxx':
case 'c':
case 'h':
case 'hpp':
return cpp();
case 'css':
case 'scss':
case 'less':
return css();
case 'html':
case 'htm':
return html();
case 'json':
return json();
case 'md':
case 'mdx':
return markdown();
case 'yaml':
case 'yml':
return yaml();
default:
return undefined;
}
};
export function FileViewerContent({ path, content }: FileViewerContentProps) {
const langExt = getLanguageExtension(path);
const langExt = getCodeMirrorExtensionFromPath(path);
const extensions: Extension[] = [
EditorView.lineWrapping,
EditorView.editable.of(false),
+3 -2
View File
@@ -1,5 +1,6 @@
'use client';
import { memo } from 'react';
import { IconChevronDown } from '@tabler/icons-react';
import { Button } from '@kandev/ui/button';
import {
@@ -17,7 +18,7 @@ type ModelSelectorProps = {
sessionId: string | null;
};
export function ModelSelector({ sessionId }: ModelSelectorProps) {
export const ModelSelector = memo(function ModelSelector({ sessionId }: ModelSelectorProps) {
// Ensure settings data (agents with profiles) is loaded
useSettingsData(true);
@@ -129,5 +130,5 @@ export function ModelSelector({ sessionId }: ModelSelectorProps) {
</DropdownMenuContent>
</DropdownMenu>
);
}
});
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { IconStack2, IconPlus, IconStar } from '@tabler/icons-react';
import { Button } from '@kandev/ui/button';
import {
@@ -92,7 +92,7 @@ type SessionsDropdownProps = {
onSetPrimary?: (sessionId: string) => void;
};
export function SessionsDropdown({
export const SessionsDropdown = memo(function SessionsDropdown({
taskId,
activeSessionId = null,
taskTitle = '',
@@ -323,4 +323,4 @@ export function SessionsDropdown({
/>
</>
);
}
});
+3 -3
View File
@@ -1,6 +1,6 @@
'use client';
import { type ReactNode } from 'react';
import { memo, type ReactNode } from 'react';
import { IconChevronRight } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
@@ -13,7 +13,7 @@ type SidebarButtonProps = {
compact?: boolean;
};
export function SidebarButton({
export const SidebarButton = memo(function SidebarButton({
icon,
label,
count,
@@ -60,4 +60,4 @@ export function SidebarButton({
)}
</button>
);
}
});
+34 -2
View File
@@ -9,12 +9,13 @@ import { TaskChangesPanel } from './task-changes-panel';
import { TaskPlanPanel } from './task-plan-panel';
import { FileViewerContent } from './file-viewer-content';
import { PassthroughTerminal } from './passthrough-terminal';
import type { OpenFileTab } from '@/lib/types/backend';
import type { OpenFileTab, FileContentResponse } from '@/lib/types/backend';
import { FILE_EXTENSION_COLORS } from '@/lib/types/backend';
import { useAppStore } from '@/components/state-provider';
import { SessionTabs, type SessionTab } from '@/components/session-tabs';
import { approveSessionAction } from '@/app/actions/workspaces';
import { getWebSocketClient } from '@/lib/ws/connection';
import { requestFileContent } from '@/lib/ws/workspace-files';
import type { SelectedDiff } from './task-layout';
@@ -160,6 +161,37 @@ export const TaskCenterPanel = memo(function TaskCenterPanel({
}
}, [leftTab, handleTabChange]);
// Handler for opening files from chat (tool read messages)
const handleOpenFileFromChat = useCallback(async (filePath: string) => {
const client = getWebSocketClient();
const currentSessionId = activeSessionId;
if (!client || !currentSessionId) return;
try {
const response: FileContentResponse = await requestFileContent(client, currentSessionId, filePath);
const fileName = filePath.split('/').pop() || filePath;
setOpenFileTabs((prev) => {
// If file is already open, just switch to it
if (prev.some((t) => t.path === filePath)) {
return prev;
}
// Add new tab (LRU eviction at max 4)
const maxTabs = 4;
const newTab: OpenFileTab = {
path: filePath,
name: fileName,
content: response.content,
};
const newTabs = prev.length >= maxTabs ? [...prev.slice(1), newTab] : [...prev, newTab];
return newTabs;
});
setLeftTab(`file:${filePath}`);
} catch (error) {
console.error('Failed to open file from chat:', error);
}
}, [activeSessionId]);
const tabs: SessionTab[] = useMemo(() => {
const staticTabs: SessionTab[] = [
{
@@ -235,7 +267,7 @@ export const TaskCenterPanel = memo(function TaskCenterPanel({
<PassthroughTerminal key={activeSessionId} sessionId={sessionId} />
</div>
) : (
<TaskChatPanel sessionId={sessionId} />
<TaskChatPanel sessionId={sessionId} onOpenFile={handleOpenFileFromChat} />
)
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
@@ -14,6 +14,7 @@ import { Button } from '@kandev/ui/button';
import { SessionPanelContent } from '@kandev/ui/pannel-session';
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { cn } from '@/lib/utils';
import { getLanguageFromPath } from '@/lib/languages';
import { getLocalStorage, setLocalStorage } from '@/lib/local-storage';
import { useAppStore } from '@/components/state-provider';
import { useSessionGitStatus } from '@/hooks/domains/session/use-session-git-status';
@@ -115,18 +116,6 @@ const TaskChangesPanel = memo(function TaskChangesPanel({
const selectedDiffContent = selectedDiff?.content ?? selectedFile?.diff ?? '';
const isSingleDiffSelected = Boolean(selectedDiffPath && (hasProvidedContent || selectedFile));
// Helper to get file language from extension
const getFileLang = (path: string) => {
const ext = path.split('.').pop() || '';
const langMap: Record<string, string> = {
ts: 'typescript', tsx: 'tsx', js: 'javascript', jsx: 'jsx',
py: 'python', go: 'go', rs: 'rust', java: 'java',
cpp: 'cpp', c: 'c', css: 'css', html: 'html',
json: 'json', md: 'markdown', yaml: 'yaml', yml: 'yaml',
};
return langMap[ext] || 'plaintext';
};
const hasUncommitted = uncommittedFiles.length > 0;
const hasCommitted = committedFiles.length > 0;
const hasAnyChanges = hasUncommitted || hasCommitted;
@@ -251,8 +240,8 @@ const TaskChangesPanel = memo(function TaskChangesPanel({
<DiffView
data={{
hunks: parseDiffIntoHunks(selectedDiffContent, selectedDiffPath!),
oldFile: { fileName: selectedDiffPath!, fileLang: getFileLang(selectedDiffPath!) },
newFile: { fileName: selectedDiffPath!, fileLang: getFileLang(selectedDiffPath!) },
oldFile: { fileName: selectedDiffPath!, fileLang: getLanguageFromPath(selectedDiffPath!) },
newFile: { fileName: selectedDiffPath!, fileLang: getLanguageFromPath(selectedDiffPath!) },
}}
diffViewMode={diffModeEnum}
diffViewTheme={diffTheme}
@@ -276,7 +265,7 @@ const TaskChangesPanel = memo(function TaskChangesPanel({
</div>
{uncommittedFiles.map((file) => {
if (!file.diff) return null;
const fileLang = getFileLang(file.path);
const fileLang = getLanguageFromPath(file.path);
// Include diff length in key to force re-render when content changes
const diffKey = `uncommitted-${file.path}-${file.diff.length}`;
return (
@@ -314,7 +303,7 @@ const TaskChangesPanel = memo(function TaskChangesPanel({
</div>
{committedFiles.map((file) => {
if (!file.diff) return null;
const fileLang = getFileLang(file.path);
const fileLang = getLanguageFromPath(file.path);
// Include diff length in key to force re-render when content changes
const diffKey = `committed-${file.path}-${file.diff.length}`;
return (
+10 -4
View File
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState, memo } from 'react';
import { getWebSocketClient } from '@/lib/ws/connection';
import { useSessionMessages } from '@/hooks/domains/session/use-session-messages';
import { useSettingsData } from '@/hooks/domains/settings/use-settings-data';
@@ -15,11 +15,13 @@ import { ChatInputContainer } from '@/components/task/chat/chat-input-container'
type TaskChatPanelProps = {
onSend?: (message: string) => void;
sessionId?: string | null;
onOpenFile?: (path: string) => void;
};
export function TaskChatPanel({
export const TaskChatPanel = memo(function TaskChatPanel({
onSend,
sessionId = null,
onOpenFile,
}: TaskChatPanelProps) {
const [planModeEnabled, setPlanModeEnabled] = useState(false);
const [isSending, setIsSending] = useState(false);
@@ -44,7 +46,7 @@ export function TaskChatPanel({
const { messages, isLoading: messagesLoading } = useSessionMessages(resolvedSessionId);
// Process messages (filtering, todos, etc.)
const { allMessages, permissionsByToolCallId, todoItems, agentMessageCount, pendingClarification } = useProcessedMessages(
const { allMessages, groupedItems, permissionsByToolCallId, childrenByParentToolCallId, todoItems, agentMessageCount, pendingClarification } = useProcessedMessages(
messages,
taskId,
resolvedSessionId,
@@ -114,13 +116,17 @@ export function TaskChatPanel({
return (
<>
<VirtualizedMessageList
items={groupedItems}
messages={allMessages}
permissionsByToolCallId={permissionsByToolCallId}
childrenByParentToolCallId={childrenByParentToolCallId}
taskId={taskId ?? undefined}
sessionId={resolvedSessionId}
messagesLoading={messagesLoading}
isWorking={isWorking}
sessionState={session?.state}
worktreePath={session?.worktree_path}
onOpenFile={onOpenFile}
/>
<div className="flex flex-col gap-2 mt-2">
@@ -149,4 +155,4 @@ export function TaskChatPanel({
</div>
</>
);
}
});
+3 -3
View File
@@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { memo, useState } from 'react';
import { IconArchive, IconLoader2 } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import type { TaskState } from '@/lib/types/http';
@@ -43,7 +43,7 @@ function formatRelativeTime(dateString: string): string {
return date.toLocaleDateString();
}
export function TaskItem({
export const TaskItem = memo(function TaskItem({
title,
description,
state,
@@ -167,4 +167,4 @@ export function TaskItem({
</div>
</div>
);
}
});
+17 -9
View File
@@ -1,6 +1,6 @@
'use client';
import { memo, useMemo, useState } from 'react';
import { memo, useMemo, useState, useCallback } from 'react';
import { Group, Panel, type Layout } from 'react-resizable-panels';
import { useDefaultLayout } from '@/lib/layout/use-default-layout';
import { TaskCenterPanel } from './task-center-panel';
@@ -57,13 +57,21 @@ export const TaskLayout = memo(function TaskLayout({
);
const hasDevScript = Boolean(repository?.dev_script?.trim());
const handleSelectDiff = (path: string, content?: string) => {
const handleSelectDiff = useCallback((path: string, content?: string) => {
setSelectedDiff({ path, content });
};
}, []);
const handleOpenFile = (file: OpenFileTab) => {
const handleOpenFile = useCallback((file: OpenFileTab) => {
setOpenFileRequest(file);
};
}, []);
const handleDiffHandled = useCallback(() => {
setSelectedDiff(null);
}, []);
const handleFileOpenHandled = useCallback(() => {
setOpenFileRequest(null);
}, []);
const topFilesPanel = (
<TaskFilesPanel
@@ -134,8 +142,8 @@ export const TaskLayout = memo(function TaskLayout({
<TaskCenterPanel
selectedDiff={selectedDiff}
openFileRequest={openFileRequest}
onDiffHandled={() => setSelectedDiff(null)}
onFileOpenHandled={() => setOpenFileRequest(null)}
onDiffHandled={handleDiffHandled}
onFileOpenHandled={handleFileOpenHandled}
/>
</Panel>
<Panel id="preview" minSize="470px" className="min-h-0 min-w-0">
@@ -148,8 +156,8 @@ export const TaskLayout = memo(function TaskLayout({
<TaskCenterPanel
selectedDiff={selectedDiff}
openFileRequest={openFileRequest}
onDiffHandled={() => setSelectedDiff(null)}
onFileOpenHandled={() => setOpenFileRequest(null)}
onDiffHandled={handleDiffHandled}
onFileOpenHandled={handleFileOpenHandled}
sessionId={sessionId}
/>
</Panel>
@@ -2,13 +2,13 @@
import { useEffect, useMemo, useState } from 'react';
import '@git-diff-view/react/styles/diff-view.css';
import { TooltipProvider } from '@kandev/ui/tooltip';
import { TaskTopBar } from '@/components/task/task-top-bar';
import { TaskLayout } from '@/components/task/task-layout';
import { DebugOverlay } from '@/components/debug-overlay';
import type { Repository, Task } from '@/lib/types/http';
import type { KanbanState } from '@/lib/state/slices';
import { DEBUG_UI } from '@/lib/config';
import { TooltipProvider } from '@kandev/ui/tooltip';
import { useRepositories } from '@/hooks/domains/workspace/use-repositories';
import { useSessionAgent } from '@/hooks/domains/session/use-session-agent';
import { useSessionResumption } from '@/hooks/domains/session/use-session-resumption';
@@ -1,7 +1,7 @@
'use client';
import { useCallback, useMemo, useState } from 'react';
import type { TaskState, Workspace, Repository, TaskSession, BoardSnapshot } from '@/lib/types/http';
import { useCallback, useMemo, useState, memo } from 'react';
import type { TaskState, Workspace, Repository, TaskSession, BoardSnapshot, Task } from '@/lib/types/http';
import type { KanbanState } from '@/lib/state/slices';
import { TaskSwitcher } from './task-switcher';
import { BoardSwitcher } from './board-switcher';
@@ -15,6 +15,47 @@ import { linkToSession } from '@/lib/links';
import { listTaskSessions, fetchBoardSnapshot, listBoards } from '@/lib/api';
import { useTasks } from '@/hooks/use-tasks';
// Extracted component to isolate dialog state from sidebar
type NewTaskButtonProps = {
workspaceId: string | null;
boardId: string | null;
columns: Array<{ id: string; title: string; color?: string; autoStartAgent?: boolean }>;
onSuccess: (task: Task, mode: 'create' | 'edit', meta?: { taskSessionId?: string | null }) => void;
};
const NewTaskButton = memo(function NewTaskButton({
workspaceId,
boardId,
columns,
onSuccess,
}: NewTaskButtonProps) {
const [dialogOpen, setDialogOpen] = useState(false);
return (
<>
<Button
size="sm"
variant="outline"
className="h-6 gap-1 cursor-pointer"
onClick={() => setDialogOpen(true)}
>
<IconPlus className="h-4 w-4" />
Task
</Button>
<TaskCreateDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
mode="task"
workspaceId={workspaceId}
boardId={boardId}
defaultColumnId={columns[0]?.id ?? null}
columns={columns}
onSuccess={onSuccess}
/>
</>
);
});
type TaskSessionSidebarProps = {
workspaceId: string | null;
boardId: string | null;
@@ -54,7 +95,7 @@ function sortByUpdatedAtDesc<T extends { updated_at?: string | null }>(items: T[
});
}
export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarProps) {
export const TaskSessionSidebar = memo(function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarProps) {
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const sessionsById = useAppStore((state) => state.taskSessions.items);
@@ -75,7 +116,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP
}
return activeTaskId;
}, [activeSessionId, activeTaskId, sessionsById]);
const [taskDialogOpen, setTaskDialogOpen] = useState(false);
const kanbanBoardId = useAppStore((state) => state.kanban.boardId);
const kanbanIsLoading = useAppStore((state) => state.kanban.isLoading ?? false);
// Consider loading if explicitly loading OR if board IDs mismatch (mid-switch)
@@ -228,6 +268,50 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP
);
// Handle workspace change - find first board and navigate to most recent task's session
// Memoized columns for NewTaskButton to prevent re-renders
const dialogColumns = useMemo(
() => columns.map((step: KanbanState['steps'][number]) => ({
id: step.id,
title: step.title,
color: step.color,
autoStartAgent: step.autoStartAgent,
})),
[columns]
);
// Memoized success handler for NewTaskButton
const handleTaskCreated = useCallback(
(task: Task, _mode: 'create' | 'edit', meta?: { taskSessionId?: string | null }) => {
store.setState((state) => {
if (state.kanban.boardId !== task.board_id) return state;
const nextTask = {
id: task.id,
workflowStepId: task.workflow_step_id,
title: task.title,
description: task.description,
position: task.position ?? 0,
state: task.state,
repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
};
return {
...state,
kanban: {
...state.kanban,
tasks: state.kanban.tasks.some((item: KanbanState['tasks'][number]) => item.id === task.id)
? state.kanban.tasks.map((item: KanbanState['tasks'][number]) => (item.id === task.id ? nextTask : item))
: [...state.kanban.tasks, nextTask],
},
};
});
setActiveTask(task.id);
if (meta?.taskSessionId) {
setActiveSession(task.id, meta.taskSessionId);
updateUrl(meta.taskSessionId);
}
},
[store, setActiveTask, setActiveSession, updateUrl]
);
const handleWorkspaceChange = useCallback(
async (newWorkspaceId: string) => {
if (newWorkspaceId === workspaceId) return;
@@ -303,15 +387,12 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP
onSelect={handleWorkspaceChange}
/>
</div>
<Button
size="sm"
variant="outline"
className="h-6 gap-1 cursor-pointer"
onClick={() => setTaskDialogOpen(true)}
>
<IconPlus className="h-4 w-4" />
Task
</Button>
<NewTaskButton
workspaceId={workspaceId}
boardId={boardId}
columns={dialogColumns}
onSuccess={handleTaskCreated}
/>
</div>
<div className="flex-1 min-h-0 overflow-y-auto space-y-4 pt-3">
<TaskSwitcher
@@ -336,43 +417,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP
</div>
)}
</SessionPanel>
<TaskCreateDialog
open={taskDialogOpen}
onOpenChange={setTaskDialogOpen}
mode="task"
workspaceId={workspaceId}
boardId={boardId}
defaultColumnId={columns[0]?.id ?? null}
columns={columns.map((step: KanbanState['steps'][number]) => ({ id: step.id, title: step.title, color: step.color, autoStartAgent: step.autoStartAgent }))}
onSuccess={(task, _mode, meta) => {
store.setState((state) => {
if (state.kanban.boardId !== task.board_id) return state;
const nextTask = {
id: task.id,
workflowStepId: task.workflow_step_id,
title: task.title,
description: task.description,
position: task.position ?? 0,
state: task.state,
repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
};
return {
...state,
kanban: {
...state.kanban,
tasks: state.kanban.tasks.some((item: KanbanState['tasks'][number]) => item.id === task.id)
? state.kanban.tasks.map((item: KanbanState['tasks'][number]) => (item.id === task.id ? nextTask : item))
: [...state.kanban.tasks, nextTask],
},
};
});
setActiveTask(task.id);
if (meta?.taskSessionId) {
setActiveSession(task.id, meta.taskSessionId);
updateUrl(meta.taskSessionId);
}
}}
/>
</>
);
}
});
+3 -3
View File
@@ -1,6 +1,6 @@
'use client';
import { useMemo, useState } from 'react';
import { memo, useMemo, useState } from 'react';
import type { TaskState } from '@/lib/types/http';
import { truncateRepoPath } from '@/lib/utils';
import { SidebarButton } from './sidebar-button';
@@ -53,7 +53,7 @@ function TaskSwitcherSkeleton() {
);
}
export function TaskSwitcher({
export const TaskSwitcher = memo(function TaskSwitcher({
tasks,
columns,
activeTaskId,
@@ -161,4 +161,4 @@ export function TaskSwitcher({
)}
</div>
);
}
});
+13 -16
View File
@@ -1,8 +1,9 @@
import { useCallback } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { listTaskSessionMessages } from '@/lib/api';
import { useAppStore } from '@/components/state-provider';
export function useLazyLoadMessages(sessionId: string | null) {
// Use refs for values that should not trigger callback recreation
const hasMore = useAppStore((state) =>
sessionId ? state.messages.metaBySession[sessionId]?.hasMore ?? false : false
);
@@ -12,16 +13,24 @@ export function useLazyLoadMessages(sessionId: string | null) {
const isLoading = useAppStore((state) =>
sessionId ? state.messages.metaBySession[sessionId]?.isLoading ?? false : false
);
// Store current values in refs to avoid recreating loadMore on every state change
const stateRef = useRef({ hasMore, oldestCursor, isLoading });
useEffect(() => {
stateRef.current = { hasMore, oldestCursor, isLoading };
}, [hasMore, oldestCursor, isLoading]);
const prependMessages = useAppStore((state) => state.prependMessages);
const setMessagesMetadata = useAppStore((state) => state.setMessagesMetadata);
// Stable loadMore - only depends on sessionId and store actions
const loadMore = useCallback(async () => {
const { hasMore, isLoading, oldestCursor } = stateRef.current;
if (!sessionId || !hasMore || isLoading || !oldestCursor) {
console.log('[useLazyLoadMessages] Cannot load more:', { sessionId, hasMore, isLoading, oldestCursor });
return 0;
}
console.log('[useLazyLoadMessages] Loading more messages before:', oldestCursor);
setMessagesMetadata(sessionId, { isLoading: true });
try {
const response = await listTaskSessionMessages(sessionId, {
@@ -29,21 +38,9 @@ export function useLazyLoadMessages(sessionId: string | null) {
before: oldestCursor,
sort: 'desc',
});
console.log('[useLazyLoadMessages] Received response:', {
count: response.messages?.length,
hasMore: response.has_more,
cursor: response.cursor,
});
const orderedMessages = [...(response.messages ?? [])].reverse();
// After reversing, orderedMessages[0] is the oldest message in this batch
const newOldestCursor = orderedMessages[0]?.id ?? null;
console.log('[useLazyLoadMessages] Prepending messages:', {
count: orderedMessages.length,
newOldestCursor,
hasMore: response.has_more,
firstMsgId: orderedMessages[0]?.id,
lastMsgId: orderedMessages[orderedMessages.length - 1]?.id,
});
prependMessages(sessionId, orderedMessages, {
hasMore: response.has_more,
oldestCursor: newOldestCursor,
@@ -54,7 +51,7 @@ export function useLazyLoadMessages(sessionId: string | null) {
setMessagesMetadata(sessionId, { isLoading: false });
return 0;
}
}, [sessionId, hasMore, isLoading, oldestCursor, prependMessages, setMessagesMetadata]);
}, [sessionId, prependMessages, setMessagesMetadata]);
return { loadMore, hasMore, isLoading };
}
+119 -2
View File
@@ -1,5 +1,27 @@
import { useMemo } from 'react';
import type { Message, ClarificationRequestMetadata } from '@/lib/types/http';
import type { Message, ClarificationRequestMetadata, MessageType } from '@/lib/types/http';
import type { ToolCallMetadata } from '@/components/task/chat/types';
// Activity types that get grouped together
const ACTIVITY_MESSAGE_TYPES: Set<MessageType> = new Set([
'thinking',
'tool_call',
'tool_edit',
'tool_read',
'tool_execute',
'tool_search',
]);
export type TurnGroup = {
type: 'turn_group';
id: string;
turnId: string | null;
messages: Message[];
};
export type RenderItem =
| { type: 'message'; message: Message }
| TurnGroup;
export function useProcessedMessages(
messages: Message[],
@@ -35,6 +57,33 @@ export function useProcessedMessages(
return map;
}, [messages]);
// Build a map of parent_tool_call_id → child messages for subagent nesting.
// When an agent sends parent_tool_use_id, child tools should be nested under the parent Task.
const childrenByParentToolCallId = useMemo(() => {
const map = new Map<string, Message[]>();
for (const message of messages) {
const metadata = message.metadata as ToolCallMetadata | undefined;
const parentId = metadata?.parent_tool_call_id;
if (parentId) {
const children = map.get(parentId) || [];
children.push(message);
map.set(parentId, children);
}
}
return map;
}, [messages]);
// Build a set of message IDs that are children of a subagent (should not render at top level)
const subagentChildIds = useMemo(() => {
const set = new Set<string>();
for (const children of childrenByParentToolCallId.values()) {
for (const child of children) {
set.add(child.id);
}
}
return set;
}, [childrenByParentToolCallId]);
// Find pending clarification request (the most recent one that is still pending)
// This will be rendered in the input area, not in the message list
const pendingClarification = useMemo(() => {
@@ -55,8 +104,14 @@ export function useProcessedMessages(
// Permission requests are only hidden if they have a matching tool_call in the messages
// (so they can be displayed inline). Standalone permissions are shown as separate messages.
// Pending clarification requests are also hidden (shown in input area instead).
// Child messages of subagents are hidden at top level (rendered nested under parent).
const visibleMessages = useMemo(() => {
return messages.filter((message) => {
// Hide child messages of subagents (they render nested under parent Task tool)
if (subagentChildIds.has(message.id)) {
return false;
}
// Hide pending clarification request (it's shown in input area)
if (message.type === 'clarification_request') {
const metadata = message.metadata as ClarificationRequestMetadata | undefined;
@@ -71,6 +126,10 @@ export function useProcessedMessages(
message.type === 'message' ||
message.type === 'content' ||
message.type === 'tool_call' ||
message.type === 'tool_read' ||
message.type === 'tool_edit' ||
message.type === 'tool_execute' ||
message.type === 'tool_search' ||
message.type === 'progress' ||
message.type === 'status' ||
message.type === 'error' ||
@@ -90,7 +149,7 @@ export function useProcessedMessages(
return false;
});
}, [messages, toolCallIds]);
}, [messages, toolCallIds, subagentChildIds]);
// Create a synthetic "user" message for the task description
const taskDescriptionMessage: Message | null = useMemo(() => {
@@ -130,11 +189,69 @@ export function useProcessedMessages(
return visibleMessages.filter((c) => c.author_type !== 'user').length;
}, [visibleMessages]);
// Group consecutive activity messages (thinking + tool types) with same turn_id
// Only create groups if 2+ activity messages exist consecutively with the same turn_id
// Messages without turn_id are NOT grouped
const groupedItems = useMemo<RenderItem[]>(() => {
const items: RenderItem[] = [];
let currentGroup: Message[] = [];
let currentTurnId: string | null = null;
const flushGroup = () => {
if (currentGroup.length >= 2) {
// Create a turn group - use first message ID for unique ID
const groupTurnId = currentGroup[0].turn_id;
const firstMsgId = currentGroup[0].id;
items.push({
type: 'turn_group',
// Use first message ID to ensure unique group IDs even within same turn
id: `turn-group-${firstMsgId}`,
turnId: groupTurnId ?? null,
messages: currentGroup,
});
} else if (currentGroup.length === 1) {
// Single message, don't group
items.push({ type: 'message', message: currentGroup[0] });
}
currentGroup = [];
currentTurnId = null;
};
for (const message of allMessages) {
const isActivity = message.type && ACTIVITY_MESSAGE_TYPES.has(message.type);
const messageTurnId = message.turn_id ?? null;
// Only group activity messages that have an actual turn_id
if (isActivity && messageTurnId) {
// Check if this continues the current group (same turn_id)
if (currentGroup.length > 0 && currentTurnId === messageTurnId) {
currentGroup.push(message);
} else {
// Flush previous group and start new one
flushGroup();
currentGroup = [message];
currentTurnId = messageTurnId;
}
} else {
// Non-activity message or activity without turn_id breaks the group
flushGroup();
items.push({ type: 'message', message });
}
}
// Flush any remaining group
flushGroup();
return items;
}, [allMessages]);
return {
visibleMessages,
allMessages,
groupedItems,
toolCallIds,
permissionsByToolCallId,
childrenByParentToolCallId,
todoItems,
agentMessageCount,
pendingClarification,
+202
View File
@@ -0,0 +1,202 @@
/**
* Centralized language utilities for file extension mapping and syntax highlighting.
*/
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import { go } from '@codemirror/lang-go';
import { rust } from '@codemirror/lang-rust';
import { java } from '@codemirror/lang-java';
import { cpp } from '@codemirror/lang-cpp';
import { css } from '@codemirror/lang-css';
import { html } from '@codemirror/lang-html';
import { json } from '@codemirror/lang-json';
import { markdown } from '@codemirror/lang-markdown';
import { yaml } from '@codemirror/lang-yaml';
import type { Extension } from '@codemirror/state';
/**
* Map of file extensions to language identifiers.
* Used for syntax highlighting and language detection.
*/
export const EXTENSION_TO_LANGUAGE: Record<string, string> = {
// JavaScript/TypeScript
js: 'javascript',
mjs: 'javascript',
cjs: 'javascript',
jsx: 'jsx',
ts: 'typescript',
mts: 'typescript',
cts: 'typescript',
tsx: 'tsx',
// Python
py: 'python',
pyw: 'python',
pyi: 'python',
// Go
go: 'go',
// Rust
rs: 'rust',
// Ruby
rb: 'ruby',
erb: 'ruby',
// Java/JVM
java: 'java',
kt: 'kotlin',
kts: 'kotlin',
scala: 'scala',
groovy: 'groovy',
// Swift
swift: 'swift',
// C/C++
c: 'c',
h: 'c',
cpp: 'cpp',
cc: 'cpp',
cxx: 'cpp',
hpp: 'cpp',
hxx: 'cpp',
// C#
cs: 'csharp',
// PHP
php: 'php',
// Web
html: 'html',
htm: 'html',
css: 'css',
scss: 'scss',
sass: 'sass',
less: 'less',
// Data formats
json: 'json',
jsonc: 'json',
yaml: 'yaml',
yml: 'yaml',
xml: 'xml',
toml: 'toml',
ini: 'ini',
env: 'properties',
// Markup
md: 'markdown',
mdx: 'markdown',
// Shell
sh: 'bash',
bash: 'bash',
zsh: 'bash',
fish: 'fish',
// SQL
sql: 'sql',
// Docker
dockerfile: 'dockerfile',
// GraphQL
graphql: 'graphql',
gql: 'graphql',
// Misc
vue: 'vue',
svelte: 'svelte',
};
/**
* Get the language identifier from a file extension.
* @param ext - File extension (without the dot)
* @returns Language identifier or 'plaintext' if unknown
*/
export function getLanguageFromExtension(ext: string): string {
return EXTENSION_TO_LANGUAGE[ext.toLowerCase()] || 'plaintext';
}
/**
* Get the language identifier from a file path.
* @param filePath - Full or relative file path
* @returns Language identifier or 'plaintext' if unknown
*/
export function getLanguageFromPath(filePath: string): string {
const ext = filePath.split('.').pop()?.toLowerCase() || '';
return getLanguageFromExtension(ext);
}
/**
* Get the CodeMirror language extension for a given language identifier.
* @param language - Language identifier (e.g., 'typescript', 'python')
* @returns CodeMirror Extension or undefined if no extension available
*/
export function getCodeMirrorExtension(language: string): Extension | undefined {
const lang = language.toLowerCase();
switch (lang) {
case 'javascript':
case 'js':
return javascript();
case 'jsx':
return javascript({ jsx: true });
case 'typescript':
case 'ts':
return javascript({ typescript: true });
case 'tsx':
return javascript({ jsx: true, typescript: true });
case 'python':
case 'py':
return python();
case 'go':
case 'golang':
return go();
case 'rust':
case 'rs':
return rust();
case 'java':
return java();
case 'cpp':
case 'c++':
case 'c':
case 'cc':
case 'cxx':
return cpp();
case 'css':
case 'scss':
case 'sass':
case 'less':
return css();
case 'html':
case 'htm':
return html();
case 'json':
case 'jsonc':
return json();
case 'markdown':
case 'md':
case 'mdx':
return markdown();
case 'yaml':
case 'yml':
return yaml();
default:
return undefined;
}
}
/**
* Get the CodeMirror language extension directly from a file path.
* @param filePath - Full or relative file path
* @returns CodeMirror Extension or undefined if no extension available
*/
export function getCodeMirrorExtensionFromPath(filePath: string): Extension | undefined {
const language = getLanguageFromPath(filePath);
return getCodeMirrorExtension(language);
}
@@ -47,9 +47,19 @@ export const createSessionSlice: StateCreator<
if (!draft.messages.bySession[sessionId]) {
draft.messages.bySession[sessionId] = [];
}
const existing = draft.messages.bySession[sessionId].find((m) => m.id === message.id);
if (!existing) {
const existingIndex = draft.messages.bySession[sessionId].findIndex((m) => m.id === message.id);
if (existingIndex === -1) {
// New message - add it
draft.messages.bySession[sessionId].push(message);
} else {
// Message exists - merge, but don't overwrite defined values with undefined
// This handles duplicate events from multiple sources
const existing = draft.messages.bySession[sessionId][existingIndex];
for (const key of Object.keys(message) as Array<keyof typeof message>) {
if (message[key] !== undefined) {
(existing as Record<string, unknown>)[key] = message[key];
}
}
}
}),
updateMessage: (message) =>
@@ -59,7 +69,16 @@ export const createSessionSlice: StateCreator<
if (messages) {
const index = messages.findIndex((m) => m.id === message.id);
if (index !== -1) {
messages[index] = message;
// Merge update with existing message, but don't overwrite defined values with undefined
// This handles the case where some event sources don't include turn_id
const existing = messages[index];
const merged = { ...existing };
for (const key of Object.keys(message) as Array<keyof typeof message>) {
if (message[key] !== undefined) {
(merged as Record<string, unknown>)[key] = message[key];
}
}
messages[index] = merged;
}
}
}),
@@ -144,13 +163,19 @@ export const createSessionSlice: StateCreator<
}),
setTaskSession: (session) =>
set((draft) => {
// Merge with existing session data to preserve fields like agent_profile_id and agent_profile_snapshot
// Merge with existing session data to preserve fields like agent_profile_id, worktree info, etc.
const existingSession = draft.taskSessions.items[session.id];
const mergedSession = existingSession
? {
...existingSession,
...session,
// Preserve fields that may not be included in partial updates from WebSocket events
agent_profile_snapshot: session.agent_profile_snapshot ?? existingSession.agent_profile_snapshot,
worktree_id: session.worktree_id ?? existingSession.worktree_id,
worktree_path: session.worktree_path ?? existingSession.worktree_path,
worktree_branch: session.worktree_branch ?? existingSession.worktree_branch,
repository_id: session.repository_id ?? existingSession.repository_id,
base_branch: session.base_branch ?? existingSession.base_branch,
}
: session;
+1
View File
@@ -150,6 +150,7 @@ export type MessageAddedPayload = {
task_id: string;
message_id: string;
session_id: string;
turn_id?: string;
author_type: 'user' | 'agent';
author_id?: string;
content: string;
+1
View File
@@ -462,6 +462,7 @@ export type MessageType =
| 'tool_call'
| 'tool_edit'
| 'tool_read'
| 'tool_search'
| 'tool_execute'
| 'progress'
| 'log'
+37
View File
@@ -165,3 +165,40 @@ export function formatRelativeTime(dateString: string): string {
if (diffDay < 7) return `${diffDay}d ago`;
return date.toLocaleDateString();
}
/**
* Convert an absolute file path to a relative path based on a workspace root.
* If the path is within the workspace, returns the relative portion.
* Otherwise, returns the original path (with home directory formatting applied).
*/
export function toRelativePath(absolutePath: string, workspaceRoot?: string | null): string {
if (!absolutePath) return absolutePath;
if (!workspaceRoot) return formatUserHomePath(absolutePath);
// Normalize paths for comparison
const normalizedPath = absolutePath.replace(/\\/g, '/');
const normalizedRoot = workspaceRoot.replace(/\\/g, '/').replace(/\/$/, '');
// Check if path is within the workspace
if (normalizedPath.startsWith(normalizedRoot + '/')) {
// Return the relative portion (strip workspace root)
return normalizedPath.slice(normalizedRoot.length + 1);
}
// Path is outside workspace, use home path formatting
return formatUserHomePath(absolutePath);
}
/**
* Transform any absolute paths in a string to relative paths based on workspace root.
* Useful for titles/descriptions that may contain embedded file paths.
*/
export function transformPathsInText(text: string, workspaceRoot?: string | null): string {
if (!text || !workspaceRoot) return text;
const normalizedRoot = workspaceRoot.replace(/\\/g, '/').replace(/\/$/, '');
// Match the workspace root followed by a path (non-whitespace characters)
const pattern = new RegExp(normalizedRoot.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '/([^\\s]+)', 'g');
return text.replace(pattern, (_, relativePart) => relativePart);
}
+2
View File
@@ -14,6 +14,7 @@ export function registerMessagesHandlers(store: StoreApi<AppState>): WsHandlers
id: payload.message_id,
session_id: payload.session_id,
task_id: payload.task_id,
turn_id: payload.turn_id,
author_type: payload.author_type,
author_id: payload.author_id,
content: payload.content,
@@ -32,6 +33,7 @@ export function registerMessagesHandlers(store: StoreApi<AppState>): WsHandlers
id: payload.message_id,
session_id: payload.session_id,
task_id: payload.task_id,
turn_id: payload.turn_id,
author_type: payload.author_type,
author_id: payload.author_id,
content: payload.content,
+4
View File
@@ -19,6 +19,8 @@ export function registerTurnsHandlers(store: StoreApi<AppState>): WsHandlers {
created_at: payload.created_at,
updated_at: payload.updated_at,
});
// Track this as the active turn for the session
store.getState().setActiveTurn(payload.session_id, payload.id);
},
'session.turn.completed': (message) => {
const payload = message.payload;
@@ -30,6 +32,8 @@ export function registerTurnsHandlers(store: StoreApi<AppState>): WsHandlers {
payload.id,
payload.completed_at || new Date().toISOString()
);
// Clear the active turn when it completes
store.getState().setActiveTurn(payload.session_id, null);
},
};
}