Nick Meslovich / Products / Gravitas

acp.go

92.3 KB · raw

package main

import (
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

type ModelOption struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type ModeOption struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

type ThoughtLevelOption struct {
	Value string `json:"value"`
	Name  string `json:"name"`
}

type CommandInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

type TierInfo struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	UpgradeURI string `json:"upgradeUri,omitempty"`
}

type UsageStats struct {
	InputTokens       int64 `json:"input_tokens"`
	OutputTokens      int64 `json:"output_tokens"`
	CachedReadTokens  int64 `json:"cached_read_tokens"`
	CachedWriteTokens int64 `json:"cached_write_tokens"`
	ThoughtTokens     int64 `json:"thought_tokens"`
	TotalTokens       int64 `json:"total_tokens"`
	Turns             int   `json:"turns"`
}

type ContextUsage struct {
	Used int64 `json:"used"`
	Size int64 `json:"size"`
}

type ToolCallRecord struct {
	ID        string      `json:"id"`
	Name      string      `json:"name"`
	Title     string      `json:"title,omitempty"`
	Kind      string      `json:"kind,omitempty"`
	Status    string      `json:"status,omitempty"`
	Args      interface{} `json:"args,omitempty"`
	Output    string      `json:"output,omitempty"`
	IsError   bool        `json:"is_error,omitempty"`
	Locations interface{} `json:"locations,omitempty"`
}

type ChatMessage struct {
	Role      string           `json:"role"` // "user", "assistant", "system"
	Text      string           `json:"text"`
	Thought   string           `json:"thought,omitempty"`
	Tools     []ToolCallRecord `json:"tools,omitempty"`
	Timestamp string           `json:"timestamp,omitempty"`
	Images    int              `json:"images,omitempty"`
}

type SessionSummary struct {
	ID               string `json:"id"`
	Title            string `json:"title"`
	Cwd              string `json:"cwd"`
	UpdatedAt        string `json:"updated_at"`
	UpdatedEpoch     int64  `json:"updated"`
	Messages         int    `json:"messages,omitempty"`
	Preview          string `json:"preview,omitempty"`
	Busy             bool   `json:"busy,omitempty"`
	TurnID           string `json:"turn_id,omitempty"`
	Activity         string `json:"activity,omitempty"`
	StartedAt        int64  `json:"started_at,omitempty"`
	PendingApprovals int    `json:"pending_approvals,omitempty"`
	PendingInputs    int    `json:"pending_inputs,omitempty"`
	Model            string `json:"model,omitempty"`
	Mode             string `json:"mode,omitempty"`
}

type ActiveTurnSummary struct {
	TurnID           string `json:"turn_id"`
	SessionID        string `json:"session_id"`
	Title            string `json:"title,omitempty"`
	StartedAt        int64  `json:"started_at"`
	Activity         string `json:"activity"`
	Seq              int64  `json:"seq"`
	PendingApprovals int    `json:"pending_approvals"`
	PendingInputs    int    `json:"pending_inputs"`
}

type ActiveTurnSnapshot struct {
	TurnID    string           `json:"turn_id"`
	SessionID string           `json:"session_id"`
	StartedAt int64            `json:"started_at"`
	Seq       int64            `json:"seq"`
	Activity  string           `json:"activity"`
	UserText  string           `json:"user_text,omitempty"`
	Images    int              `json:"images,omitempty"`
	Text      string           `json:"text"`
	Thought   string           `json:"thought,omitempty"`
	Tools     []ToolCallRecord `json:"tools,omitempty"`
}

type StreamEvent struct {
	Type      string
	SessionID string
	TurnID    string
	Seq       int64
	Data      map[string]interface{}
}

type PendingApproval struct {
	ID           string                   `json:"id"`
	SessionID    string                   `json:"session_id"`
	SessionTitle string                   `json:"session_title,omitempty"`
	Tool         string                   `json:"tool"`
	Title        string                   `json:"title"`
	Kind         string                   `json:"kind"`
	Args         interface{}              `json:"args"`
	Options      []map[string]interface{} `json:"options"`
	ReplyCh      chan string              `json:"-"`
}

type PendingInput struct {
	ID           string                 `json:"id"`
	SessionID    string                 `json:"session_id"`
	SessionTitle string                 `json:"session_title,omitempty"`
	Question     string                 `json:"question"`
	Schema       map[string]interface{} `json:"schema,omitempty"`
	Mode         string                 `json:"mode,omitempty"`
	ReplyCh      chan interface{}       `json:"-"`
}

type sessionState struct {
	ID                     string
	Title                  string
	Cwd                    string
	UpdatedAt              time.Time
	Model                  string
	Mode                   string
	ThoughtLevel           string
	AvailableThoughtLevels []ThoughtLevelOption
	Usage                  UsageStats
	ContextUsage           ContextUsage
	Messages               []ChatMessage
	DiskSig                string
	NeedLoad               bool
	Loaded                 bool
	ActiveTurn             *activeTurn
	ActiveCancel           context.CancelFunc
	LastCompletedTurnID    string
}

type streamEntry struct {
	id int64
	fn func(StreamEvent)
}

type AcpManager struct {
	agyBin    string
	geminiDir string
	mockMode  bool

	startMu sync.Mutex // serializes subprocess startup/restart

	mu           sync.Mutex
	cmd          *exec.Cmd
	stdin        io.WriteCloser
	acpConnected bool
	stderrBuf    []string
	nextID       atomic.Int64
	nextTurnSeq  atomic.Int64
	nextStreamID atomic.Int64
	pendingRPC   map[int64]chan rpcResponse

	// Global defaults & last-focused session fallback
	agentVersion           string
	cwd                    string
	additionalDirs         []string
	activeSessionID        string
	activeTitle            string
	defaultModel           string
	currentModel           string
	currentMode            string
	thoughtLevel           string
	availableModels        []ModelOption
	availableModes         []ModeOption
	availableThoughtLevels []ThoughtLevelOption
	commands               []CommandInfo
	tier                   TierInfo

	// Per-session state (supports unlimited concurrent chats)
	sessions        map[string]*sessionState
	deletedSessions map[string]bool

	// Per-session stream callbacks for session/update routing
	streamMu       sync.Mutex
	sessionStreams map[string]streamEntry

	// Global event hub for persistent /api/events subscribers
	hubMu   sync.Mutex
	hubSubs map[chan StreamEvent]struct{}

	// Pending interactive requests from server
	interactiveMu sync.Mutex
	approvals     map[string]*PendingApproval
	inputs        map[string]*PendingInput
}

type rpcResponse struct {
	Result json.RawMessage
	Error  *rpcError
}

type rpcError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

type rpcEnvelope struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *rpcError       `json:"error,omitempty"`
}

func NewAcpManager(agyBin, geminiDir, initialCwd string, mockMode bool) *AcpManager {
	if initialCwd == "" {
		if d, err := os.Getwd(); err == nil {
			initialCwd = d
		} else {
			initialCwd = "."
		}
	}
	if abs, err := filepath.Abs(initialCwd); err == nil {
		initialCwd = abs
	}
	m := &AcpManager{
		agyBin:                 agyBin,
		geminiDir:              geminiDir,
		mockMode:               mockMode,
		cwd:                    initialCwd,
		pendingRPC:             make(map[int64]chan rpcResponse),
		sessions:               make(map[string]*sessionState),
		deletedSessions:        make(map[string]bool),
		sessionStreams:         make(map[string]streamEntry),
		hubSubs:                make(map[chan StreamEvent]struct{}),
		approvals:              make(map[string]*PendingApproval),
		inputs:                 make(map[string]*PendingInput),
		agentVersion:           "",
		currentModel:           "gemini-4-neon-high",
		currentMode:            "default",
		thoughtLevel:           "high",
		availableModels:        defaultModels(),
		availableModes:         defaultModes(),
		availableThoughtLevels: defaultThoughtLevels(),
		commands:               defaultCommands(),
	}
	if defMod := m.loadPersistedDefaultModel(); defMod != "" {
		m.defaultModel = defMod
		m.currentModel = m.resolveModelIDLocked(defMod, "")
		if tl := thoughtLevelFromModelID(m.currentModel); tl != "" {
			m.thoughtLevel = tl
		}
	}
	return m
}

func (m *AcpManager) getOrCreateSessionLocked(sid string) *sessionState {
	if sid == "" {
		return nil
	}
	if s, ok := m.sessions[sid]; ok {
		return s
	}
	s := &sessionState{
		ID:                     sid,
		Title:                  "New conversation",
		Cwd:                    m.cwd,
		UpdatedAt:              time.Now(),
		Model:                  m.currentModel,
		Mode:                   m.currentMode,
		ThoughtLevel:           m.thoughtLevel,
		AvailableThoughtLevels: append([]ThoughtLevelOption{}, m.availableThoughtLevels...),
	}
	m.sessions[sid] = s
	return s
}

func (m *AcpManager) resolveSessionIDLocked(reqSID string) string {
	reqSID = strings.TrimSpace(reqSID)
	if reqSID != "" {
		return reqSID
	}
	return m.activeSessionID
}

func defaultModels() []ModelOption {
	return []ModelOption{
		{ID: "gemini-4-neon-high", Name: "Gemini 4 Neon (High)"},
		{ID: "gemini-4-neon-xhigh", Name: "Gemini 4 Neon (XHigh)"},
		{ID: "gemini-4-neon-medium", Name: "Gemini 4 Neon (Medium)"},
		{ID: "gemini-4-neon-low", Name: "Gemini 4 Neon (Low)"},
		{ID: "gemini-4-argon-medium", Name: "Gemini 4 Argon (Medium)"},
		{ID: "gemini-4-argon-high", Name: "Gemini 4 Argon (High)"},
		{ID: "gemini-4-argon-low", Name: "Gemini 4 Argon (Low)"},
		{ID: "gemini-4-hydrogen-high", Name: "Gemini 4 Hydrogen (High)"},
		{ID: "gemini-4-hydrogen-xhigh", Name: "Gemini 4 Hydrogen (XHigh)"},
		{ID: "gemini-4-hydrogen-medium", Name: "Gemini 4 Hydrogen (Medium)"},
		{ID: "gemini-4-hydrogen-low", Name: "Gemini 4 Hydrogen (Low)"},
		{ID: "gemini-pro-orchestrator-neon", Name: "Orchestrator (Neon)"},
		{ID: "gemini-pro-orchestrator-g1-pro", Name: "Orchestrator (Argon)"},
		{ID: "gemini-3.8-flash-high", Name: "Gemini 3.8 Flash (High)"},
		{ID: "gemini-3.8-flash-medium", Name: "Gemini 3.8 Flash (Medium)"},
		{ID: "gemini-3.8-flash-low", Name: "Gemini 3.8 Flash (Low)"},
		{ID: "claude-opus-5-5-low", Name: "Claude Opus 5.5 (Low)"},
		{ID: "claude-opus-5-5-medium", Name: "Claude Opus 5.5 (Medium)"},
		{ID: "claude-opus-5-5-high", Name: "Claude Opus 5.5 (High)"},
		{ID: "claude-sonnet-5-5-low", Name: "Claude Sonnet 5.5 (Low)"},
		{ID: "claude-sonnet-5-5-medium", Name: "Claude Sonnet 5.5 (Medium)"},
		{ID: "claude-sonnet-5-5-high", Name: "Claude Sonnet 5.5 (High)"},
		{ID: "gpt-oss-120b-medium", Name: "GPT-OSS 120B (Medium)"},
	}
}

func defaultModes() []ModeOption {
	return []ModeOption{
		{ID: "default", Name: "Default", Description: "Ask before edits and commands, per your permission settings."},
		{ID: "accept-edits", Name: "Accept edits", Description: "Approve file edits in the workspace without asking."},
		{ID: "auto", Name: "Auto", Description: "Approve edits and safe commands; ask before irreversible actions."},
		{ID: "plan", Name: "Plan", Description: "Plan carefully before executing a task."},
	}
}

func defaultThoughtLevels() []ThoughtLevelOption {
	return []ThoughtLevelOption{
		{Value: "low", Name: "Low"},
		{Value: "medium", Name: "Medium"},
		{Value: "high", Name: "High"},
		{Value: "xhigh", Name: "Extra"},
	}
}

func defaultCommands() []CommandInfo {
	return []CommandInfo{
		{Name: "goal", Description: "Pursue a long-running goal thoroughly until completion"},
		{Name: "compact", Description: "Compact conversation history to free context window"},
		{Name: "plan", Description: "Create a detailed step-by-step plan before execution"},
		{Name: "grill-me", Description: "Interactive interview to align on design decisions"},
		{Name: "boost", Description: "Deep thinking, strategic planning, and rigorous verification"},
		{Name: "teamwork", Description: "Coordinate a swarm of autonomous agents in parallel"},
		{Name: "browser", Description: "Browse and interact with web applications"},
		{Name: "schedule", Description: "Schedule a recurring instruction or timer"},
		{Name: "learn", Description: "Persist a lesson or setup rule for future tasks"},
	}
}

func thoughtLevelFromModelID(id string) string {
	lower := strings.ToLower(strings.TrimSpace(id))
	for _, lvl := range []string{"xhigh", "high", "medium", "low"} {
		if strings.HasSuffix(lower, "-"+lvl) {
			return lvl
		}
	}
	return ""
}

func stripThoughtSuffix(id string) string {
	lower := strings.ToLower(strings.TrimSpace(id))
	for _, lvl := range []string{"-xhigh", "-high", "-medium", "-low"} {
		if strings.HasSuffix(lower, lvl) {
			return id[:len(id)-len(lvl)]
		}
	}
	return id
}

// resolveModelIDLocked maps a model ID, base model name, or display name to a canonical model ID.
// Must be called with m.mu held.
func (m *AcpManager) resolveModelIDLocked(raw string, preferredThought string) string {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return m.currentModel
	}
	for _, mod := range m.availableModels {
		if strings.EqualFold(mod.ID, raw) {
			return mod.ID
		}
	}
	for _, mod := range m.availableModels {
		if strings.EqualFold(mod.Name, raw) {
			return mod.ID
		}
	}
	base := stripThoughtSuffix(raw)
	tl := strings.TrimSpace(preferredThought)
	if tl == "" {
		tl = m.thoughtLevel
	}
	if tl != "" {
		candidate := base + "-" + tl
		for _, mod := range m.availableModels {
			if strings.EqualFold(mod.ID, candidate) {
				return mod.ID
			}
		}
	}
	if m.currentModel != "" && strings.EqualFold(stripThoughtSuffix(m.currentModel), base) {
		return m.currentModel
	}
	prefix := strings.ToLower(base) + "-"
	for _, mod := range m.availableModels {
		if strings.HasPrefix(strings.ToLower(mod.ID), prefix) {
			return mod.ID
		}
	}
	return raw
}

// --- Global Event Hub ---

func (m *AcpManager) SubscribeHub() (chan StreamEvent, func()) {
	ch := make(chan StreamEvent, 512)
	m.hubMu.Lock()
	m.hubSubs[ch] = struct{}{}
	m.hubMu.Unlock()
	unsub := func() {
		m.hubMu.Lock()
		if _, ok := m.hubSubs[ch]; ok {
			delete(m.hubSubs, ch)
			close(ch)
		}
		m.hubMu.Unlock()
	}
	return ch, unsub
}

func (m *AcpManager) HubSubscriberCount() int {
	m.hubMu.Lock()
	defer m.hubMu.Unlock()
	return len(m.hubSubs)
}

func (m *AcpManager) BroadcastHub(ev StreamEvent) {
	if ev.SessionID != "" {
		if ev.Data == nil {
			ev.Data = map[string]interface{}{}
		}
		if _, exists := ev.Data["session_id"]; !exists {
			ev.Data["session_id"] = ev.SessionID
		}
	}
	m.hubMu.Lock()
	for ch := range m.hubSubs {
		select {
		case ch <- ev:
		default:
			select {
			case <-ch:
			default:
			}
			select {
			case ch <- ev:
			default:
			}
		}
	}
	m.hubMu.Unlock()
}

func (m *AcpManager) BroadcastStateSync(reason string) {
	m.BroadcastHub(StreamEvent{
		Type: "state_sync",
		Data: map[string]interface{}{
			"reason": reason,
		},
	})
}

func (m *AcpManager) BroadcastSessionUpdated(sessionID, reason string) {
	m.BroadcastHub(StreamEvent{
		Type:      "session_updated",
		SessionID: sessionID,
		Data: map[string]interface{}{
			"session_id": sessionID,
			"reason":     reason,
		},
	})
}

func (m *AcpManager) BroadcastSessionsActivity(reason string) {
	running := m.RunningSessionsSnapshot()
	m.BroadcastHub(StreamEvent{
		Type: "sessions_activity",
		Data: map[string]interface{}{
			"reason":           reason,
			"running_sessions": running,
		},
	})
}

func (m *AcpManager) RunningSessionsSnapshot() []ActiveTurnSummary {
	appCounts, inpCounts := m.pendingCountsBySession()

	m.mu.Lock()
	defer m.mu.Unlock()
	out := make([]ActiveTurnSummary, 0)
	for sid, sess := range m.sessions {
		if sess.ActiveTurn == nil {
			continue
		}
		snap := sess.ActiveTurn.Summary(appCounts[sid], inpCounts[sid])
		snap.Title = sess.Title
		out = append(out, snap)
	}
	sort.Slice(out, func(i, j int) bool {
		return out[i].StartedAt < out[j].StartedAt
	})
	return out
}

func (m *AcpManager) pendingCountsBySession() (map[string]int, map[string]int) {
	appCounts := make(map[string]int)
	inpCounts := make(map[string]int)
	m.interactiveMu.Lock()
	for _, pa := range m.approvals {
		appCounts[pa.SessionID]++
	}
	for _, pi := range m.inputs {
		inpCounts[pi.SessionID]++
	}
	m.interactiveMu.Unlock()
	return appCounts, inpCounts
}

// StartDiskWatcher polls idle sessions' transcript files on disk when clients are connected,
// so turns completed in the CLI appear automatically in the PWA.
func (m *AcpManager) StartDiskWatcher(ctx context.Context) {
	if m.mockMode {
		return
	}
	go func() {
		ticker := time.NewTicker(3 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				if m.HubSubscriberCount() == 0 {
					continue
				}
				m.mu.Lock()
				var candidates []string
				for sid, sess := range m.sessions {
					if sess.ActiveTurn == nil && !m.deletedSessions[sid] {
						candidates = append(candidates, sid)
					}
				}
				m.mu.Unlock()

				for _, sid := range candidates {
					if changed := m.SyncSessionFromDisk(sid); changed {
						m.BroadcastSessionUpdated(sid, "disk_transcript_updated")
					}
				}
			}
		}
	}()
}

// EnsureStarted starts the `agy acp` child process and initializes it. Serialized via startMu.
func (m *AcpManager) EnsureStarted(ctx context.Context) error {
	if m.mockMode {
		m.mu.Lock()
		m.acpConnected = true
		if m.activeSessionID == "" {
			sid := "mock-session-1"
			m.activeSessionID = sid
			m.activeTitle = "New conversation"
			s := m.getOrCreateSessionLocked(sid)
			s.Title = m.activeTitle
			s.Cwd = m.cwd
			s.UpdatedAt = time.Now()
			s.Loaded = true
		}
		m.mu.Unlock()
		return nil
	}

	m.mu.Lock()
	alreadyRunning := m.cmd != nil && m.cmd.Process != nil && m.stdin != nil && m.acpConnected
	m.mu.Unlock()
	if alreadyRunning {
		return nil
	}

	m.startMu.Lock()
	defer m.startMu.Unlock()

	m.mu.Lock()
	alreadyRunning = m.cmd != nil && m.cmd.Process != nil && m.stdin != nil && m.acpConnected
	cwd := m.cwd
	m.mu.Unlock()
	if alreadyRunning {
		return nil
	}

	cmd := exec.Command(m.agyBin, "acp")
	cmd.Dir = cwd
	cmd.Env = append(os.Environ(), "NO_COLOR=1")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return fmt.Errorf("stdin pipe: %w", err)
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("stdout pipe: %w", err)
	}
	stderrPipe, err := cmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("stderr pipe: %w", err)
	}

	if err := cmd.Start(); err != nil {
		return fmt.Errorf("start %s acp: %w", m.agyBin, err)
	}

	m.mu.Lock()
	m.cmd = cmd
	m.stdin = stdin
	m.acpConnected = false
	m.stderrBuf = nil
	m.pendingRPC = make(map[int64]chan rpcResponse)
	for _, s := range m.sessions {
		s.Loaded = false
	}
	m.mu.Unlock()

	go m.stderrLoop(stderrPipe)
	go m.readLoop(stdout, cmd)

	initCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()

	initParams := map[string]interface{}{
		"protocolVersion": 1,
		"clientCapabilities": map[string]interface{}{
			"auth":        map[string]interface{}{"terminal": true},
			"elicitation": map[string]interface{}{"form": true},
		},
	}
	raw, err := m.callRPC(initCtx, "initialize", initParams)
	if err != nil {
		m.killProcess(cmd, stdin)
		return fmt.Errorf("acp initialize: %w", err)
	}
	var initRes struct {
		AgentInfo struct {
			Name    string `json:"name"`
			Version string `json:"version"`
		} `json:"agentInfo"`
	}
	m.mu.Lock()
	if json.Unmarshal(raw, &initRes) == nil && initRes.AgentInfo.Version != "" {
		m.agentVersion = initRes.AgentInfo.Version
	}
	m.acpConnected = true
	hasActive := m.activeSessionID != ""
	defModel := m.defaultModel
	agentVer := m.agentVersion
	m.mu.Unlock()

	if !hasActive {
		if b, err := os.ReadFile(m.settingsPath()); err == nil {
			var disk map[string]interface{}
			if json.Unmarshal(b, &disk) == nil {
				m.mu.Lock()
				if mod, ok := disk["model"].(string); ok && mod != "" && defModel == "" {
					resolved := m.resolveModelIDLocked(mod, "")
					m.currentModel = resolved
					if tl := thoughtLevelFromModelID(resolved); tl != "" {
						m.thoughtLevel = tl
					}
				}
				if mode, ok := disk["agentMode"].(string); ok && mode != "" {
					m.currentMode = mode
				}
				m.mu.Unlock()
			}
		}
		if defModel != "" {
			m.mu.Lock()
			resolved := m.resolveModelIDLocked(defModel, "")
			m.currentModel = resolved
			if tl := thoughtLevelFromModelID(resolved); tl != "" {
				m.thoughtLevel = tl
			}
			m.mu.Unlock()
		}
	}

	m.BroadcastHub(StreamEvent{
		Type: "bridge_status",
		Data: map[string]interface{}{
			"acp_connected": true,
			"agent_version": agentVer,
		},
	})
	return nil
}

func (m *AcpManager) killProcess(cmd *exec.Cmd, stdin io.WriteCloser) {
	if stdin != nil {
		_ = stdin.Close()
	}
	if cmd != nil && cmd.Process != nil {
		_ = cmd.Process.Kill()
		_, _ = cmd.Process.Wait()
	}
	m.mu.Lock()
	if m.cmd == cmd {
		m.cmd = nil
		m.stdin = nil
		m.acpConnected = false
	}
	m.mu.Unlock()
}

func (m *AcpManager) RestartACP(ctx context.Context) error {
	m.cancelPendingInteractive()

	m.mu.Lock()
	cmd := m.cmd
	stdin := m.stdin
	sid := m.activeSessionID
	var cancels []context.CancelFunc
	var turns []*activeTurn
	for _, s := range m.sessions {
		if s.ActiveCancel != nil {
			cancels = append(cancels, s.ActiveCancel)
			s.ActiveCancel = nil
		}
		if s.ActiveTurn != nil {
			turns = append(turns, s.ActiveTurn)
			s.ActiveTurn = nil
		}
		s.Loaded = false
	}
	m.cmd = nil
	m.stdin = nil
	m.acpConnected = false
	m.mu.Unlock()

	for _, c := range cancels {
		c()
	}
	for _, turn := range turns {
		turn.emit(StreamEvent{
			Type: "cancelled",
			Data: map[string]interface{}{"reason": "ACP engine restarted"},
		})
		turn.close()
	}
	if !m.mockMode {
		if stdin != nil {
			_ = stdin.Close()
		}
		if cmd != nil && cmd.Process != nil {
			_ = cmd.Process.Kill()
			_, _ = cmd.Process.Wait()
		}
	}

	if err := m.EnsureStarted(ctx); err != nil {
		return err
	}
	if sid != "" && !m.mockMode {
		_, _, _ = m.OpenSession(ctx, sid)
	}
	m.BroadcastStateSync("acp_restarted")
	return nil
}

func (m *AcpManager) Stop() {
	m.cancelPendingInteractive()

	m.mu.Lock()
	cmd := m.cmd
	stdin := m.stdin
	var cancels []context.CancelFunc
	var turns []*activeTurn
	for _, s := range m.sessions {
		if s.ActiveCancel != nil {
			cancels = append(cancels, s.ActiveCancel)
			s.ActiveCancel = nil
		}
		if s.ActiveTurn != nil {
			turns = append(turns, s.ActiveTurn)
			s.ActiveTurn = nil
		}
	}
	m.cmd = nil
	m.stdin = nil
	m.acpConnected = false
	m.mu.Unlock()

	for _, c := range cancels {
		c()
	}
	for _, turn := range turns {
		turn.close()
	}
	if stdin != nil {
		_ = stdin.Close()
	}
	if cmd != nil && cmd.Process != nil {
		_ = cmd.Process.Kill()
		_, _ = cmd.Process.Wait()
	}
}

func (m *AcpManager) stderrLoop(r io.Reader) {
	br := bufio.NewReaderSize(r, 16*1024)
	for {
		line, err := br.ReadString('\n')
		if len(line) > 0 {
			trimmed := strings.TrimRight(line, "\r\n")
			_, _ = fmt.Fprintln(os.Stderr, "[agy acp]", trimmed)
			m.mu.Lock()
			m.stderrBuf = append(m.stderrBuf, trimmed)
			if len(m.stderrBuf) > 40 {
				m.stderrBuf = m.stderrBuf[len(m.stderrBuf)-40:]
			}
			m.mu.Unlock()
		}
		if err != nil {
			return
		}
	}
}

func (m *AcpManager) lastStderrSummary() string {
	m.mu.Lock()
	defer m.mu.Unlock()
	if len(m.stderrBuf) == 0 {
		return ""
	}
	start := len(m.stderrBuf) - 4
	if start < 0 {
		start = 0
	}
	return strings.Join(m.stderrBuf[start:], " | ")
}

func (m *AcpManager) readLoop(r io.Reader, cmd *exec.Cmd) {
	br := bufio.NewReaderSize(r, 256*1024)
	for {
		lineBytes, err := br.ReadBytes('\n')
		if len(lineBytes) > 0 {
			line := strings.TrimSpace(string(lineBytes))
			if line != "" {
				var env rpcEnvelope
				if jerr := json.Unmarshal([]byte(line), &env); jerr == nil {
					if env.Method != "" && len(env.ID) > 0 && string(env.ID) != "null" {
						go m.handleServerRequest(env)
					} else if env.Method != "" {
						m.handleNotification(env.Method, env.Params)
					} else if len(env.ID) > 0 {
						var id int64
						if uerr := json.Unmarshal(env.ID, &id); uerr == nil {
							m.mu.Lock()
							ch, ok := m.pendingRPC[id]
							if ok {
								delete(m.pendingRPC, id)
							}
							m.mu.Unlock()
							if ok {
								ch <- rpcResponse{Result: env.Result, Error: env.Error}
							}
						}
					}
				}
			}
		}
		if err != nil {
			break
		}
	}

	if cmd != nil && cmd.Process != nil {
		_ = cmd.Wait()
	}

	m.cancelPendingInteractive()

	stderrDetail := m.lastStderrSummary()
	exitMsg := "ACP process exited"
	if stderrDetail != "" {
		exitMsg = fmt.Sprintf("ACP process exited (%s)", stderrDetail)
	}

	m.mu.Lock()
	wasCurrent := m.cmd == cmd
	if wasCurrent {
		m.cmd = nil
		m.stdin = nil
		m.acpConnected = false
		for _, s := range m.sessions {
			s.Loaded = false
		}
		for id, ch := range m.pendingRPC {
			delete(m.pendingRPC, id)
			ch <- rpcResponse{Error: &rpcError{Code: -32000, Message: exitMsg}}
		}
	}
	m.mu.Unlock()

	if wasCurrent {
		m.BroadcastHub(StreamEvent{
			Type: "bridge_status",
			Data: map[string]interface{}{
				"acp_connected": false,
				"message":       exitMsg,
			},
		})
	}
}

func isTransportError(err error) bool {
	if err == nil {
		return false
	}
	msg := strings.ToLower(err.Error())
	return strings.Contains(msg, "acp process exited") ||
		strings.Contains(msg, "acp process not running") ||
		strings.Contains(msg, "broken pipe") ||
		strings.Contains(msg, "file already closed") ||
		strings.Contains(msg, "eof")
}

func (m *AcpManager) callRPC(ctx context.Context, method string, params interface{}) (json.RawMessage, error) {
	id := m.nextID.Add(1)
	ch := make(chan rpcResponse, 1)

	m.mu.Lock()
	stdin := m.stdin
	if stdin == nil {
		m.mu.Unlock()
		return nil, errors.New("ACP process not running")
	}
	m.pendingRPC[id] = ch
	m.mu.Unlock()

	req := map[string]interface{}{
		"jsonrpc": "2.0",
		"id":      id,
		"method":  method,
		"params":  params,
	}
	data, err := json.Marshal(req)
	if err != nil {
		m.mu.Lock()
		delete(m.pendingRPC, id)
		m.mu.Unlock()
		return nil, err
	}
	data = append(data, '\n')

	m.mu.Lock()
	if m.stdin == nil {
		delete(m.pendingRPC, id)
		m.mu.Unlock()
		return nil, errors.New("ACP process not running")
	}
	_, err = m.stdin.Write(data)
	m.mu.Unlock()
	if err != nil {
		m.mu.Lock()
		delete(m.pendingRPC, id)
		m.mu.Unlock()
		return nil, err
	}

	select {
	case <-ctx.Done():
		m.mu.Lock()
		delete(m.pendingRPC, id)
		m.mu.Unlock()
		return nil, ctx.Err()
	case resp := <-ch:
		if resp.Error != nil {
			return nil, fmt.Errorf("ACP error (%d): %s", resp.Error.Code, resp.Error.Message)
		}
		return resp.Result, nil
	}
}

func (m *AcpManager) sendNotification(method string, params interface{}) error {
	req := map[string]interface{}{
		"jsonrpc": "2.0",
		"method":  method,
		"params":  params,
	}
	data, err := json.Marshal(req)
	if err != nil {
		return err
	}
	data = append(data, '\n')

	m.mu.Lock()
	stdin := m.stdin
	if stdin == nil {
		m.mu.Unlock()
		return errors.New("ACP process not running")
	}
	_, err = stdin.Write(data)
	m.mu.Unlock()
	return err
}

func (m *AcpManager) sendRPCResponse(rawID json.RawMessage, result interface{}, rpcErr *rpcError) {
	resp := map[string]interface{}{
		"jsonrpc": "2.0",
		"id":      rawID,
	}
	if rpcErr != nil {
		resp["error"] = rpcErr
	} else {
		resp["result"] = result
	}
	data, err := json.Marshal(resp)
	if err != nil {
		return
	}
	data = append(data, '\n')
	m.mu.Lock()
	stdin := m.stdin
	if stdin != nil {
		_, _ = stdin.Write(data)
	}
	m.mu.Unlock()
}

func (m *AcpManager) sessionTitleByID(sid string) string {
	if sid == "" {
		return ""
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if s, ok := m.sessions[sid]; ok && s.Title != "" {
		return s.Title
	}
	return "Conversation " + shortID(sid)
}

func (m *AcpManager) PendingApprovalsSnapshot(sessionID string) []*PendingApproval {
	m.interactiveMu.Lock()
	raw := make([]*PendingApproval, 0, len(m.approvals))
	for _, pa := range m.approvals {
		if sessionID != "" && pa.SessionID != sessionID {
			continue
		}
		cp := *pa
		raw = append(raw, &cp)
	}
	m.interactiveMu.Unlock()

	for _, pa := range raw {
		if pa.SessionTitle == "" && pa.SessionID != "" {
			pa.SessionTitle = m.sessionTitleByID(pa.SessionID)
		}
	}
	return raw
}

func (m *AcpManager) PendingInputsSnapshot(sessionID string) []*PendingInput {
	m.interactiveMu.Lock()
	raw := make([]*PendingInput, 0, len(m.inputs))
	for _, pi := range m.inputs {
		if sessionID != "" && pi.SessionID != sessionID {
			continue
		}
		cp := *pi
		raw = append(raw, &cp)
	}
	m.interactiveMu.Unlock()

	for _, pi := range raw {
		if pi.SessionTitle == "" && pi.SessionID != "" {
			pi.SessionTitle = m.sessionTitleByID(pi.SessionID)
		}
	}
	return raw
}

func (m *AcpManager) handleServerRequest(env rpcEnvelope) {
	reqIDStr := strings.Trim(string(env.ID), `"`)
	switch env.Method {
	case "session/request_permission":
		var params struct {
			SessionID string `json:"sessionId"`
			ToolCall  struct {
				ToolCallID string      `json:"toolCallId"`
				Title      string      `json:"title"`
				Kind       string      `json:"kind"`
				Status     string      `json:"status"`
				Name       string      `json:"name"`
				RawInput   interface{} `json:"rawInput"`
				Args       interface{} `json:"args"`
			} `json:"toolCall"`
			Options []map[string]interface{} `json:"options"`
		}
		_ = json.Unmarshal(env.Params, &params)
		approvalID := params.ToolCall.ToolCallID
		if approvalID == "" {
			approvalID = "perm-" + reqIDStr
		}
		toolName := params.ToolCall.Name
		if toolName == "" {
			toolName = params.ToolCall.Kind
		}
		if toolName == "" {
			toolName = "tool"
		}
		args := params.ToolCall.RawInput
		if args == nil {
			args = params.ToolCall.Args
		}
		sessTitle := m.sessionTitleByID(params.SessionID)
		pa := &PendingApproval{
			ID:           approvalID,
			SessionID:    params.SessionID,
			SessionTitle: sessTitle,
			Tool:         toolName,
			Title:        params.ToolCall.Title,
			Kind:         params.ToolCall.Kind,
			Args:         args,
			Options:      params.Options,
			ReplyCh:      make(chan string, 1),
		}
		m.interactiveMu.Lock()
		m.approvals[approvalID] = pa
		m.interactiveMu.Unlock()

		ev := StreamEvent{
			Type:      "approval",
			SessionID: pa.SessionID,
			Data: map[string]interface{}{
				"id":            pa.ID,
				"session_id":    pa.SessionID,
				"session_title": pa.SessionTitle,
				"tool":          pa.Tool,
				"title":         pa.Title,
				"kind":          pa.Kind,
				"args":          pa.Args,
				"options":       pa.Options,
				"summary":       pa.Title,
			},
		}
		if !m.emitStreamForSession(pa.SessionID, ev) {
			m.BroadcastHub(ev)
		}
		m.BroadcastSessionsActivity("approval_requested")

		optionID := <-pa.ReplyCh
		m.interactiveMu.Lock()
		delete(m.approvals, approvalID)
		m.interactiveMu.Unlock()
		m.BroadcastSessionsActivity("approval_resolved")

		if optionID == "" || optionID == "cancelled" {
			m.sendRPCResponse(env.ID, map[string]interface{}{
				"outcome": map[string]interface{}{"outcome": "cancelled"},
			}, nil)
		} else {
			m.sendRPCResponse(env.ID, map[string]interface{}{
				"outcome": map[string]interface{}{
					"outcome":  "selected",
					"optionId": optionID,
				},
			}, nil)
		}

	case "elicitation/create":
		var params struct {
			SessionID       string                 `json:"sessionId"`
			Message         string                 `json:"message"`
			RequestedSchema map[string]interface{} `json:"requestedSchema"`
			Mode            string                 `json:"mode"`
			ElicitationID   string                 `json:"elicitationId"`
		}
		_ = json.Unmarshal(env.Params, &params)
		inputID := params.ElicitationID
		if inputID == "" {
			inputID = "input-" + reqIDStr
		}
		sessTitle := m.sessionTitleByID(params.SessionID)
		pi := &PendingInput{
			ID:           inputID,
			SessionID:    params.SessionID,
			SessionTitle: sessTitle,
			Question:     params.Message,
			Schema:       params.RequestedSchema,
			Mode:         params.Mode,
			ReplyCh:      make(chan interface{}, 1),
		}
		m.interactiveMu.Lock()
		m.inputs[inputID] = pi
		m.interactiveMu.Unlock()

		ev := StreamEvent{
			Type:      "prompt",
			SessionID: pi.SessionID,
			Data: map[string]interface{}{
				"id":            pi.ID,
				"session_id":    pi.SessionID,
				"session_title": pi.SessionTitle,
				"question":      pi.Question,
				"schema":        pi.Schema,
				"mode":          pi.Mode,
			},
		}
		if !m.emitStreamForSession(pi.SessionID, ev) {
			m.BroadcastHub(ev)
		}
		m.BroadcastSessionsActivity("input_requested")

		val := <-pi.ReplyCh
		m.interactiveMu.Lock()
		delete(m.inputs, inputID)
		m.interactiveMu.Unlock()
		m.BroadcastSessionsActivity("input_resolved")

		if val == nil {
			m.sendRPCResponse(env.ID, map[string]interface{}{
				"action": "cancel",
			}, nil)
		} else {
			content := map[string]interface{}{}
			switch v := val.(type) {
			case string:
				propKey := firstSchemaProperty(pi.Schema)
				if propKey != "" {
					content[propKey] = v
				} else {
					content["answer"] = v
				}
			case map[string]interface{}:
				content = v
			default:
				content["answer"] = fmt.Sprintf("%v", v)
			}
			m.sendRPCResponse(env.ID, map[string]interface{}{
				"action":  "accept",
				"content": content,
			}, nil)
		}

	default:
		m.sendRPCResponse(env.ID, nil, &rpcError{Code: -32601, Message: "Method not supported"})
	}
}

func firstSchemaProperty(schema map[string]interface{}) string {
	if schema == nil {
		return ""
	}
	props, ok := schema["properties"].(map[string]interface{})
	if !ok || len(props) != 1 {
		return ""
	}
	for k := range props {
		return k
	}
	return ""
}

func (m *AcpManager) ResolveApproval(id string, optionID string, allow *bool) bool {
	m.interactiveMu.Lock()
	var pa *PendingApproval
	if id != "" {
		pa = m.approvals[id]
	}
	if pa == nil {
		for _, candidate := range m.approvals {
			pa = candidate
			break
		}
	}
	m.interactiveMu.Unlock()
	if pa == nil {
		return false
	}
	if optionID == "" && allow != nil {
		if *allow {
			optionID = pickOptionID(pa.Options, "allow_once", "allow")
		} else {
			optionID = pickOptionID(pa.Options, "reject_once", "reject")
		}
	}
	if optionID == "" {
		optionID = pickOptionID(pa.Options, "allow_once", "allow")
	}
	select {
	case pa.ReplyCh <- optionID:
		ev := StreamEvent{
			Type:      "approval_resolved",
			SessionID: pa.SessionID,
			Data: map[string]interface{}{
				"id":         pa.ID,
				"session_id": pa.SessionID,
				"option_id":  optionID,
			},
		}
		if !m.emitStreamForSession(pa.SessionID, ev) {
			m.BroadcastHub(ev)
		}
		return true
	default:
		return false
	}
}

func pickOptionID(options []map[string]interface{}, preferredKind, fallbackPrefix string) string {
	for _, opt := range options {
		k, _ := opt["kind"].(string)
		oid, _ := opt["optionId"].(string)
		if k == preferredKind && oid != "" {
			return oid
		}
	}
	for _, opt := range options {
		k, _ := opt["kind"].(string)
		oid, _ := opt["optionId"].(string)
		if strings.HasPrefix(k, fallbackPrefix) && oid != "" {
			return oid
		}
	}
	return preferredKind
}

func (m *AcpManager) ResolveInput(id string, value interface{}) bool {
	m.interactiveMu.Lock()
	var pi *PendingInput
	if id != "" {
		pi = m.inputs[id]
	}
	if pi == nil {
		for _, candidate := range m.inputs {
			pi = candidate
			break
		}
	}
	m.interactiveMu.Unlock()
	if pi == nil {
		return false
	}
	select {
	case pi.ReplyCh <- value:
		ev := StreamEvent{
			Type:      "input_resolved",
			SessionID: pi.SessionID,
			Data: map[string]interface{}{
				"id":         pi.ID,
				"session_id": pi.SessionID,
			},
		}
		if !m.emitStreamForSession(pi.SessionID, ev) {
			m.BroadcastHub(ev)
		}
		return true
	default:
		return false
	}
}

func (m *AcpManager) cancelPendingInteractiveForSession(sessionID string) {
	m.interactiveMu.Lock()
	type resolvedItem struct {
		id  string
		sid string
	}
	var resolvedApprovals []resolvedItem
	var resolvedInputs []resolvedItem
	for id, pa := range m.approvals {
		if sessionID != "" && pa.SessionID != sessionID {
			continue
		}
		select {
		case pa.ReplyCh <- "cancelled":
		default:
		}
		delete(m.approvals, id)
		resolvedApprovals = append(resolvedApprovals, resolvedItem{id: id, sid: pa.SessionID})
	}
	for id, pi := range m.inputs {
		if sessionID != "" && pi.SessionID != sessionID {
			continue
		}
		select {
		case pi.ReplyCh <- nil:
		default:
		}
		delete(m.inputs, id)
		resolvedInputs = append(resolvedInputs, resolvedItem{id: id, sid: pi.SessionID})
	}
	m.interactiveMu.Unlock()

	for _, item := range resolvedApprovals {
		m.BroadcastHub(StreamEvent{
			Type:      "approval_resolved",
			SessionID: item.sid,
			Data:      map[string]interface{}{"id": item.id, "session_id": item.sid},
		})
	}
	for _, item := range resolvedInputs {
		m.BroadcastHub(StreamEvent{
			Type:      "input_resolved",
			SessionID: item.sid,
			Data:      map[string]interface{}{"id": item.id, "session_id": item.sid},
		})
	}
}

func (m *AcpManager) cancelPendingInteractive() {
	m.cancelPendingInteractiveForSession("")
}

func (m *AcpManager) registerSessionStream(sid string, fn func(StreamEvent)) int64 {
	regID := m.nextStreamID.Add(1)
	m.streamMu.Lock()
	m.sessionStreams[sid] = streamEntry{id: regID, fn: fn}
	m.streamMu.Unlock()
	return regID
}

func (m *AcpManager) unregisterSessionStream(sid string, regID int64) {
	m.streamMu.Lock()
	if cur, ok := m.sessionStreams[sid]; ok && cur.id == regID {
		delete(m.sessionStreams, sid)
	}
	m.streamMu.Unlock()
}

func (m *AcpManager) emitStreamForSession(sessionID string, ev StreamEvent) bool {
	if sessionID != "" {
		ev.SessionID = sessionID
		if ev.Data == nil {
			ev.Data = map[string]interface{}{}
		}
		if _, exists := ev.Data["session_id"]; !exists {
			ev.Data["session_id"] = sessionID
		}
	}
	m.streamMu.Lock()
	entry, ok := m.sessionStreams[sessionID]
	m.streamMu.Unlock()
	if !ok || entry.fn == nil {
		return false
	}
	entry.fn(ev)
	return true
}

func (m *AcpManager) handleNotification(method string, rawParams json.RawMessage) {
	if method != "session/update" {
		return
	}
	var payload struct {
		SessionID string                 `json:"sessionId"`
		Update    map[string]interface{} `json:"update"`
	}
	if err := json.Unmarshal(rawParams, &payload); err != nil || payload.Update == nil {
		return
	}
	sid := payload.SessionID
	u := payload.Update
	kind, _ := u["sessionUpdate"].(string)

	switch kind {
	case "available_commands_update":
		if rawCmds, ok := u["availableCommands"].([]interface{}); ok {
			var cmds []CommandInfo
			for _, item := range rawCmds {
				if mItem, ok := item.(map[string]interface{}); ok {
					name, _ := mItem["name"].(string)
					desc, _ := mItem["description"].(string)
					if name != "" {
						cmds = append(cmds, CommandInfo{Name: name, Description: desc})
					}
				}
			}
			if len(cmds) > 0 {
				m.mu.Lock()
				m.commands = cmds
				m.mu.Unlock()
				ev := StreamEvent{
					Type:      "commands",
					SessionID: sid,
					Data:      map[string]interface{}{"session_id": sid, "commands": cmds},
				}
				if !m.emitStreamForSession(sid, ev) {
					m.BroadcastHub(ev)
				}
			}
		}

	case "session_info_update":
		title, _ := u["title"].(string)
		if title != "" {
			m.mu.Lock()
			if sid != "" {
				s := m.getOrCreateSessionLocked(sid)
				s.Title = title
				s.UpdatedAt = time.Now()
			}
			if sid == m.activeSessionID || m.activeSessionID == "" {
				m.activeTitle = title
			}
			m.mu.Unlock()
			ev := StreamEvent{
				Type:      "title",
				SessionID: sid,
				Data: map[string]interface{}{
					"session_id": sid,
					"title":      title,
				},
			}
			if !m.emitStreamForSession(sid, ev) {
				m.BroadcastHub(ev)
			}
		}

	case "current_mode_update":
		modeID, _ := u["currentModeId"].(string)
		if modeID != "" {
			m.mu.Lock()
			if sid != "" {
				s := m.getOrCreateSessionLocked(sid)
				s.Mode = modeID
			}
			if sid == "" || sid == m.activeSessionID {
				m.currentMode = modeID
			}
			m.mu.Unlock()
			ev := StreamEvent{
				Type:      "mode",
				SessionID: sid,
				Data:      map[string]interface{}{"session_id": sid, "mode": modeID},
			}
			if !m.emitStreamForSession(sid, ev) {
				m.BroadcastHub(ev)
			}
		}

	case "config_option_update":
		if opts, ok := u["configOptions"].([]interface{}); ok {
			m.applyConfigOptionsForSession(sid, opts)
			m.mu.Lock()
			mod := m.currentModel
			mode := m.currentMode
			tl := m.thoughtLevel
			tls := append([]ThoughtLevelOption{}, m.availableThoughtLevels...)
			if s, ok := m.sessions[sid]; ok {
				mod = s.Model
				mode = s.Mode
				tl = s.ThoughtLevel
				if len(s.AvailableThoughtLevels) > 0 {
					tls = append([]ThoughtLevelOption{}, s.AvailableThoughtLevels...)
				}
			}
			m.mu.Unlock()
			ev := StreamEvent{
				Type:      "config_options",
				SessionID: sid,
				Data: map[string]interface{}{
					"session_id":     sid,
					"model":          mod,
					"mode":           mode,
					"thought_level":  tl,
					"thought_levels": tls,
				},
			}
			if !m.emitStreamForSession(sid, ev) {
				m.BroadcastHub(ev)
			}
		}

	case "usage_update":
		used, _ := toInt64(u["used"])
		size, _ := toInt64(u["size"])
		if used > 0 || size > 0 {
			m.mu.Lock()
			if sid != "" {
				s := m.getOrCreateSessionLocked(sid)
				s.ContextUsage = ContextUsage{Used: used, Size: size}
			}
			m.mu.Unlock()
			ev := StreamEvent{
				Type:      "context_usage",
				SessionID: sid,
				Data: map[string]interface{}{
					"session_id": sid,
					"used":       used,
					"size":       size,
				},
			}
			if !m.emitStreamForSession(sid, ev) {
				m.BroadcastHub(ev)
			}
		}

	case "agent_thought_chunk":
		text := extractContentText(u["content"])
		if text != "" {
			m.emitStreamForSession(sid, StreamEvent{
				Type:      "thought",
				SessionID: sid,
				Data:      map[string]interface{}{"session_id": sid, "text": text},
			})
		}

	case "agent_message_chunk":
		text := extractContentText(u["content"])
		if text != "" {
			m.emitStreamForSession(sid, StreamEvent{
				Type:      "delta",
				SessionID: sid,
				Data:      map[string]interface{}{"session_id": sid, "text": text},
			})
		}

	case "user_message_chunk":
		text := extractContentText(u["content"])
		if text != "" {
			m.emitStreamForSession(sid, StreamEvent{
				Type:      "user_chunk",
				SessionID: sid,
				Data:      map[string]interface{}{"session_id": sid, "text": text},
			})
		}

	case "tool_call":
		tcID, _ := u["toolCallId"].(string)
		title, _ := u["title"].(string)
		tcKind, _ := u["kind"].(string)
		status, _ := u["status"].(string)
		name, _ := u["name"].(string)
		if name == "" {
			if tcKind != "" {
				name = tcKind
			} else if title != "" {
				name = title
			} else {
				name = "tool"
			}
		}
		args := u["rawInput"]
		if args == nil {
			args = u["args"]
		}
		m.emitStreamForSession(sid, StreamEvent{
			Type:      "tool",
			SessionID: sid,
			Data: map[string]interface{}{
				"session_id": sid,
				"id":         tcID,
				"name":       name,
				"title":      title,
				"kind":       tcKind,
				"status":     status,
				"args":       args,
				"locations":  u["locations"],
			},
		})

	case "tool_call_update":
		tcID, _ := u["toolCallId"].(string)
		status, _ := u["status"].(string)
		title, _ := u["title"].(string)
		tcKind, _ := u["kind"].(string)
		name, _ := u["name"].(string)
		if name == "" {
			name = tcKind
		}
		output := extractToolOutput(u["content"], u["rawOutput"])
		isErr := status == "failed" || status == "error" || status == "rejected"
		args := u["rawInput"]
		if args == nil {
			args = u["args"]
		}
		m.emitStreamForSession(sid, StreamEvent{
			Type:      "result",
			SessionID: sid,
			Data: map[string]interface{}{
				"session_id": sid,
				"id":         tcID,
				"name":       name,
				"kind":       tcKind,
				"title":      title,
				"status":     status,
				"args":       args,
				"output":     output,
				"is_error":   isErr,
				"locations":  u["locations"],
			},
		})
	}
}

func toInt64(v interface{}) (int64, bool) {
	switch val := v.(type) {
	case float64:
		return int64(val), true
	case int:
		return int64(val), true
	case int64:
		return val, true
	case json.Number:
		i, err := val.Int64()
		return i, err == nil
	}
	return 0, false
}

func extractContentText(raw interface{}) string {
	switch v := raw.(type) {
	case string:
		return v
	case map[string]interface{}:
		if t, ok := v["text"].(string); ok {
			return t
		}
	case []interface{}:
		var sb strings.Builder
		for _, item := range v {
			sb.WriteString(extractContentText(item))
		}
		return sb.String()
	}
	return ""
}

func extractToolOutput(content interface{}, rawOutput interface{}) string {
	if s := extractContentText(content); s != "" {
		return s
	}
	if arr, ok := content.([]interface{}); ok {
		var parts []string
		for _, elem := range arr {
			if m, ok := elem.(map[string]interface{}); ok {
				if inner, ok := m["content"]; ok {
					if t := extractContentText(inner); t != "" {
						parts = append(parts, t)
					}
				} else if t, ok := m["text"].(string); ok && t != "" {
					parts = append(parts, t)
				}
			}
		}
		if len(parts) > 0 {
			return strings.Join(parts, "\n")
		}
	}
	if rawOutput != nil {
		if s, ok := rawOutput.(string); ok {
			return s
		}
		if b, err := json.MarshalIndent(rawOutput, "", "  "); err == nil {
			return string(b)
		}
	}
	return ""
}

func (m *AcpManager) applySessionResponse(raw json.RawMessage, fallbackSessionID string) string {
	var res struct {
		SessionID string `json:"sessionId"`
		Models    struct {
			AvailableModels []struct {
				ModelID string `json:"modelId"`
				Name    string `json:"name"`
			} `json:"availableModels"`
			CurrentModelID string `json:"currentModelId"`
		} `json:"models"`
		Modes struct {
			CurrentModeID  string `json:"currentModeId"`
			AvailableModes []struct {
				ID          string `json:"id"`
				Name        string `json:"name"`
				Description string `json:"description"`
			} `json:"availableModes"`
		} `json:"modes"`
		ConfigOptions []interface{} `json:"configOptions"`
		Meta          struct {
			Antigravity struct {
				Tier struct {
					ID         string `json:"id"`
					Name       string `json:"name"`
					UpgradeURI string `json:"upgradeUri"`
				} `json:"tier"`
			} `json:"antigravity"`
		} `json:"_meta"`
	}
	if err := json.Unmarshal(raw, &res); err != nil {
		return fallbackSessionID
	}
	sid := res.SessionID
	if sid == "" {
		sid = fallbackSessionID
	}
	m.mu.Lock()
	if len(res.Models.AvailableModels) > 0 {
		models := make([]ModelOption, 0, len(res.Models.AvailableModels))
		for _, mod := range res.Models.AvailableModels {
			models = append(models, ModelOption{ID: mod.ModelID, Name: mod.Name})
		}
		m.availableModels = models
	}
	if len(res.Modes.AvailableModes) > 0 {
		modes := make([]ModeOption, 0, len(res.Modes.AvailableModes))
		for _, md := range res.Modes.AvailableModes {
			modes = append(modes, ModeOption{ID: md.ID, Name: md.Name, Description: md.Description})
		}
		m.availableModes = modes
	}
	if res.Meta.Antigravity.Tier.Name != "" {
		m.tier = TierInfo{
			ID:         res.Meta.Antigravity.Tier.ID,
			Name:       res.Meta.Antigravity.Tier.Name,
			UpgradeURI: res.Meta.Antigravity.Tier.UpgradeURI,
		}
	}
	var sess *sessionState
	if sid != "" {
		sess = m.getOrCreateSessionLocked(sid)
	}
	if res.Models.CurrentModelID != "" {
		if sess != nil {
			sess.Model = res.Models.CurrentModelID
			if tl := thoughtLevelFromModelID(res.Models.CurrentModelID); tl != "" {
				sess.ThoughtLevel = tl
			}
		}
		if sid == "" || sid == m.activeSessionID {
			m.currentModel = res.Models.CurrentModelID
			if tl := thoughtLevelFromModelID(res.Models.CurrentModelID); tl != "" {
				m.thoughtLevel = tl
			}
		}
	}
	if res.Modes.CurrentModeID != "" {
		if sess != nil {
			sess.Mode = res.Modes.CurrentModeID
		}
		if sid == "" || sid == m.activeSessionID {
			m.currentMode = res.Modes.CurrentModeID
		}
	}
	m.mu.Unlock()
	if len(res.ConfigOptions) > 0 {
		m.applyConfigOptionsForSession(sid, res.ConfigOptions)
	}
	return sid
}

func (m *AcpManager) applyConfigOptions(opts []interface{}) {
	m.applyConfigOptionsForSession("", opts)
}

func (m *AcpManager) applyConfigOptionsForSession(sid string, opts []interface{}) {
	m.mu.Lock()
	defer m.mu.Unlock()

	var sess *sessionState
	if sid != "" {
		sess = m.getOrCreateSessionLocked(sid)
	}
	updateGlobal := sid == "" || sid == m.activeSessionID

	var baseModel string
	var newThought string
	var parsedLevels []ThoughtLevelOption

	for _, item := range opts {
		opt, ok := item.(map[string]interface{})
		if !ok {
			continue
		}
		id, _ := opt["id"].(string)
		val, _ := opt["currentValue"].(string)

		switch id {
		case "thought_level":
			if val != "" {
				newThought = val
			}
			if rawOpts, ok := opt["options"].([]interface{}); ok && len(rawOpts) > 0 {
				for _, ro := range rawOpts {
					if om, ok := ro.(map[string]interface{}); ok {
						ov, _ := om["value"].(string)
						on, _ := om["name"].(string)
						if ov != "" {
							if on == "" {
								on = ov
							}
							parsedLevels = append(parsedLevels, ThoughtLevelOption{Value: ov, Name: on})
						}
					}
				}
			}
		case "mode":
			if val != "" {
				if sess != nil {
					sess.Mode = val
				}
				if updateGlobal {
					m.currentMode = val
				}
			}
		case "model":
			if val != "" {
				baseModel = val
			}
		}
	}

	if len(parsedLevels) > 0 {
		if sess != nil {
			sess.AvailableThoughtLevels = parsedLevels
		}
		if updateGlobal {
			m.availableThoughtLevels = parsedLevels
		}
	}

	if newThought != "" {
		if sess != nil {
			sess.ThoughtLevel = newThought
		}
		if updateGlobal {
			m.thoughtLevel = newThought
		}
	}

	curTL := newThought
	if curTL == "" {
		if sess != nil && sess.ThoughtLevel != "" {
			curTL = sess.ThoughtLevel
		} else {
			curTL = m.thoughtLevel
		}
	}

	if baseModel != "" {
		resolved := m.resolveModelIDLocked(baseModel, curTL)
		if sess != nil {
			sess.Model = resolved
		}
		if updateGlobal {
			m.currentModel = resolved
		}
	} else if newThought != "" {
		if sess != nil && sess.Model != "" {
			sess.Model = m.resolveModelIDLocked(stripThoughtSuffix(sess.Model), newThought)
		}
		if updateGlobal && m.currentModel != "" {
			m.currentModel = m.resolveModelIDLocked(stripThoughtSuffix(m.currentModel), newThought)
		}
	}
}

func (m *AcpManager) NewSession(ctx context.Context, cwd string) (string, error) {
	if cwd == "" {
		m.mu.Lock()
		cwd = m.cwd
		m.mu.Unlock()
	}
	if abs, err := filepath.Abs(cwd); err == nil {
		cwd = abs
	}

	if m.mockMode {
		m.mu.Lock()
		sid := fmt.Sprintf("mock-session-%d", time.Now().UnixNano())
		m.cwd = cwd
		m.activeSessionID = sid
		m.activeTitle = "New conversation"
		s := m.getOrCreateSessionLocked(sid)
		s.Title = m.activeTitle
		s.Cwd = cwd
		s.UpdatedAt = time.Now()
		s.Messages = []ChatMessage{}
		s.Loaded = true
		s.Usage = UsageStats{}
		s.ContextUsage = ContextUsage{}
		if m.defaultModel != "" {
			resolved := m.resolveModelIDLocked(m.defaultModel, "")
			s.Model = resolved
			m.currentModel = resolved
			if tl := thoughtLevelFromModelID(resolved); tl != "" {
				s.ThoughtLevel = tl
				m.thoughtLevel = tl
			}
		}
		m.mu.Unlock()
		m.BroadcastSessionsActivity("new_session")
		return sid, nil
	}

	if err := m.EnsureStarted(ctx); err != nil {
		return "", err
	}

	params := map[string]interface{}{
		"cwd":        cwd,
		"mcpServers": []interface{}{},
	}
	raw, err := m.callRPC(ctx, "session/new", params)
	if err != nil && isTransportError(err) {
		if rerr := m.EnsureStarted(ctx); rerr == nil {
			raw, err = m.callRPC(ctx, "session/new", params)
		}
	}
	if err != nil {
		return "", err
	}
	sid := m.applySessionResponse(raw, "")
	if sid == "" {
		return "", errors.New("empty sessionId from session/new")
	}
	m.mu.Lock()
	m.cwd = cwd
	m.activeSessionID = sid
	m.activeTitle = "New conversation"
	s := m.getOrCreateSessionLocked(sid)
	s.Title = m.activeTitle
	s.Cwd = cwd
	s.UpdatedAt = time.Now()
	s.Loaded = true
	s.Usage = UsageStats{}
	s.ContextUsage = ContextUsage{}
	if s.Messages == nil {
		s.Messages = []ChatMessage{}
	}
	if s.Model != "" {
		m.currentModel = s.Model
	}
	if s.Mode != "" {
		m.currentMode = s.Mode
	}
	if s.ThoughtLevel != "" {
		m.thoughtLevel = s.ThoughtLevel
	}
	defModel := m.defaultModel
	m.mu.Unlock()

	if defModel != "" {
		_ = m.SetModelForSession(ctx, sid, defModel)
	}
	m.BroadcastSessionsActivity("new_session")
	return sid, nil
}

func (m *AcpManager) OpenSession(ctx context.Context, sessionID string) ([]ChatMessage, string, error) {
	if sessionID == "" {
		return nil, "", errors.New("missing session id")
	}

	m.mu.Lock()
	sess := m.getOrCreateSessionLocked(sessionID)
	isBusy := sess.ActiveTurn != nil
	if isBusy {
		msgs := append([]ChatMessage{}, sess.Messages...)
		title := sess.Title
		if title == "" {
			title = "Conversation " + shortID(sessionID)
		}
		m.activeSessionID = sessionID
		m.activeTitle = title
		if sess.Cwd != "" {
			m.cwd = sess.Cwd
		}
		if sess.Model != "" {
			m.currentModel = sess.Model
		}
		if sess.Mode != "" {
			m.currentMode = sess.Mode
		}
		if sess.ThoughtLevel != "" {
			m.thoughtLevel = sess.ThoughtLevel
		}
		m.mu.Unlock()
		return msgs, title, nil
	}
	m.mu.Unlock()

	// Sync transcript from disk first (captures any turns done in CLI)
	m.SyncSessionFromDisk(sessionID)

	m.mu.Lock()
	sess = m.getOrCreateSessionLocked(sessionID)
	cwd := sess.Cwd
	if cwd == "" {
		cwd = m.cwd
	}
	alreadyLoaded := sess.Loaded
	needReload := sess.NeedLoad
	cachedMsgs := append([]ChatMessage{}, sess.Messages...)
	title := sess.Title
	if title == "" || title == "New conversation" {
		if len(cachedMsgs) > 0 {
			title = deriveTitleFromMessages(cachedMsgs, sessionID)
		} else {
			title = "Conversation " + shortID(sessionID)
		}
	}
	m.mu.Unlock()

	if !m.mockMode {
		if err := m.EnsureStarted(ctx); err != nil {
			return cachedMsgs, title, fmt.Errorf("start ACP: %w", err)
		}
		if alreadyLoaded && needReload {
			_, _ = m.callRPC(ctx, "session/close", map[string]interface{}{"sessionId": sessionID})
			m.mu.Lock()
			if s, ok := m.sessions[sessionID]; ok {
				s.Loaded = false
				s.NeedLoad = false
			}
			m.mu.Unlock()
			alreadyLoaded = false
		}
		if !alreadyLoaded {
			var loadErr error
			if len(cachedMsgs) > 0 {
				raw, err := m.callRPC(ctx, "session/resume", map[string]interface{}{
					"sessionId":  sessionID,
					"cwd":        cwd,
					"mcpServers": []interface{}{},
				})
				if err != nil && isTransportError(err) {
					if rerr := m.EnsureStarted(ctx); rerr == nil {
						raw, err = m.callRPC(ctx, "session/resume", map[string]interface{}{
							"sessionId":  sessionID,
							"cwd":        cwd,
							"mcpServers": []interface{}{},
						})
					}
				}
				if err == nil {
					m.applySessionResponse(raw, sessionID)
					m.mu.Lock()
					if s, ok := m.sessions[sessionID]; ok {
						s.Loaded = true
						s.NeedLoad = false
					}
					m.mu.Unlock()
				} else {
					replayed, lerr := m.loadWithReplay(ctx, sessionID, cwd)
					if lerr != nil {
						loadErr = fmt.Errorf("resume/load session %s: %w", shortID(sessionID), err)
					} else if len(replayed) > len(cachedMsgs) {
						cachedMsgs = replayed
					}
				}
			} else {
				replayed, lerr := m.loadWithReplay(ctx, sessionID, cwd)
				if lerr != nil {
					loadErr = lerr
				} else if len(replayed) > 0 {
					cachedMsgs = replayed
				}
			}
			if loadErr != nil && len(cachedMsgs) == 0 {
				return nil, "", loadErr
			}
		}
	}

	m.mu.Lock()
	sess = m.getOrCreateSessionLocked(sessionID)
	if len(cachedMsgs) > 0 && sess.ActiveTurn == nil {
		sess.Messages = cachedMsgs
	}
	sess.Title = title
	if cwd != "" {
		sess.Cwd = cwd
		m.cwd = cwd
	}
	m.activeSessionID = sessionID
	m.activeTitle = title
	if sess.Model != "" {
		m.currentModel = sess.Model
	}
	if sess.Mode != "" {
		m.currentMode = sess.Mode
	}
	if sess.ThoughtLevel != "" {
		m.thoughtLevel = sess.ThoughtLevel
	}
	outMsgs := append([]ChatMessage{}, sess.Messages...)
	m.mu.Unlock()

	return outMsgs, title, nil
}

func deriveTitleFromMessages(msgs []ChatMessage, sid string) string {
	for _, msg := range msgs {
		if msg.Role == "user" && strings.TrimSpace(msg.Text) != "" {
			line := strings.TrimSpace(strings.Split(msg.Text, "\n")[0])
			if len(line) > 60 {
				return line[:60] + "…"
			}
			return line
		}
	}
	return "Conversation " + shortID(sid)
}

func (m *AcpManager) loadWithReplay(ctx context.Context, sessionID, cwd string) ([]ChatMessage, error) {
	var messages []ChatMessage
	var curRole string
	var curText strings.Builder
	var curThought strings.Builder
	var curTools []ToolCallRecord
	toolIdx := make(map[string]int)

	flushAssistant := func() {
		if curRole == "assistant" && (curText.Len() > 0 || curThought.Len() > 0 || len(curTools) > 0) {
			messages = append(messages, ChatMessage{
				Role:    "assistant",
				Text:    curText.String(),
				Thought: curThought.String(),
				Tools:   curTools,
			})
			curText.Reset()
			curThought.Reset()
			curTools = nil
			toolIdx = make(map[string]int)
		}
	}
	flushUser := func() {
		if curRole == "user" && curText.Len() > 0 {
			messages = append(messages, ChatMessage{
				Role: "user",
				Text: curText.String(),
			})
			curText.Reset()
		}
	}

	regID := m.registerSessionStream(sessionID, func(ev StreamEvent) {
		switch ev.Type {
		case "user_chunk":
			if curRole != "user" {
				flushAssistant()
				curRole = "user"
			}
			if t, ok := ev.Data["text"].(string); ok {
				curText.WriteString(t)
			}
		case "thought":
			if curRole != "assistant" {
				flushUser()
				curRole = "assistant"
			}
			if t, ok := ev.Data["text"].(string); ok {
				curThought.WriteString(t)
			}
		case "delta":
			if curRole != "assistant" {
				flushUser()
				curRole = "assistant"
			}
			if t, ok := ev.Data["text"].(string); ok {
				curText.WriteString(t)
			}
		case "tool":
			if curRole != "assistant" {
				flushUser()
				curRole = "assistant"
			}
			id, _ := ev.Data["id"].(string)
			name, _ := ev.Data["name"].(string)
			title, _ := ev.Data["title"].(string)
			kind, _ := ev.Data["kind"].(string)
			status, _ := ev.Data["status"].(string)
			rec := ToolCallRecord{
				ID:     id,
				Name:   name,
				Title:  title,
				Kind:   kind,
				Status: status,
				Args:   ev.Data["args"],
			}
			if idx, ok := toolIdx[id]; ok && id != "" {
				curTools[idx] = rec
			} else {
				if id != "" {
					toolIdx[id] = len(curTools)
				}
				curTools = append(curTools, rec)
			}
		case "result":
			if curRole != "assistant" {
				flushUser()
				curRole = "assistant"
			}
			id, _ := ev.Data["id"].(string)
			output, _ := ev.Data["output"].(string)
			status, _ := ev.Data["status"].(string)
			isErr, _ := ev.Data["is_error"].(bool)
			if idx, ok := toolIdx[id]; ok && id != "" {
				curTools[idx].Output = output
				if status != "" {
					curTools[idx].Status = status
				}
				curTools[idx].IsError = isErr
			}
		}
	})

	raw, err := m.callRPC(ctx, "session/load", map[string]interface{}{
		"sessionId":  sessionID,
		"cwd":        cwd,
		"mcpServers": []interface{}{},
	})

	m.unregisterSessionStream(sessionID, regID)

	flushUser()
	flushAssistant()

	if err == nil {
		m.applySessionResponse(raw, sessionID)
		m.mu.Lock()
		if s, ok := m.sessions[sessionID]; ok {
			s.Loaded = true
			s.NeedLoad = false
		}
		m.mu.Unlock()
	}
	return messages, err
}

func (m *AcpManager) ListSessions(ctx context.Context, allWorkspaces bool) ([]SessionSummary, error) {
	seen := make(map[string]SessionSummary)

	if !m.mockMode {
		if err := m.EnsureStarted(ctx); err == nil {
			m.mu.Lock()
			cwd := m.cwd
			m.mu.Unlock()

			cwds := []string{cwd}
			if allWorkspaces {
				cwds = append(cwds, "")
			}
			for _, qCwd := range cwds {
				raw, err := m.callRPC(ctx, "session/list", map[string]interface{}{"cwd": qCwd})
				if err != nil {
					continue
				}
				var res struct {
					Sessions []struct {
						SessionID string `json:"sessionId"`
						Cwd       string `json:"cwd"`
						Title     string `json:"title"`
						UpdatedAt string `json:"updatedAt"`
					} `json:"sessions"`
				}
				if json.Unmarshal(raw, &res) == nil {
					for _, s := range res.Sessions {
						if s.SessionID == "" {
							continue
						}
						m.mu.Lock()
						deleted := m.deletedSessions[s.SessionID]
						var memTitle string
						if !deleted {
							sess := m.getOrCreateSessionLocked(s.SessionID)
							if s.Title != "" && (sess.Title == "" || sess.Title == "New conversation" || strings.HasPrefix(sess.Title, "Conversation ")) {
								sess.Title = s.Title
							}
							if s.Cwd != "" {
								sess.Cwd = s.Cwd
							}
							memTitle = sess.Title
						}
						m.mu.Unlock()
						if deleted {
							continue
						}
						ts, _ := time.Parse(time.RFC3339Nano, s.UpdatedAt)
						if ts.IsZero() {
							ts = time.Now()
						}
						title := memTitle
						if title == "" || title == "New conversation" {
							title = s.Title
						}
						if title == "" {
							title = "Conversation " + shortID(s.SessionID)
						}
						seen[s.SessionID] = SessionSummary{
							ID:           s.SessionID,
							Title:        title,
							Cwd:          s.Cwd,
							UpdatedAt:    s.UpdatedAt,
							UpdatedEpoch: ts.UnixMilli(),
						}
					}
				}
			}
		}
	}

	appCounts, inpCounts := m.pendingCountsBySession()

	// Merge in-memory sessions + live busy/activity status
	m.mu.Lock()
	for sid, sess := range m.sessions {
		if m.deletedSessions[sid] {
			continue
		}
		var entry SessionSummary
		exists := false
		if e, ok := seen[sid]; ok {
			entry = e
			exists = true
		}
		if !exists {
			up := sess.UpdatedAt
			if up.IsZero() {
				up = time.Now()
			}
			preview := ""
			if len(sess.Messages) > 0 {
				preview = sess.Messages[len(sess.Messages)-1].Text
				if len(preview) > 120 {
					preview = preview[:120] + "…"
				}
			}
			entry = SessionSummary{
				ID:           sid,
				Title:        sess.Title,
				Cwd:          sess.Cwd,
				UpdatedAt:    up.UTC().Format(time.RFC3339),
				UpdatedEpoch: up.UnixMilli(),
				Messages:     len(sess.Messages),
				Preview:      preview,
			}
		} else {
			if sess.Title != "" && sess.Title != "New conversation" {
				entry.Title = sess.Title
			}
			if len(sess.Messages) > 0 {
				entry.Messages = len(sess.Messages)
			}
			if !sess.UpdatedAt.IsZero() && sess.UpdatedAt.UnixMilli() > entry.UpdatedEpoch {
				entry.UpdatedEpoch = sess.UpdatedAt.UnixMilli()
				entry.UpdatedAt = sess.UpdatedAt.UTC().Format(time.RFC3339)
			}
		}
		entry.Model = sess.Model
		entry.Mode = sess.Mode
		entry.PendingApprovals = appCounts[sid]
		entry.PendingInputs = inpCounts[sid]
		if sess.ActiveTurn != nil {
			sum := sess.ActiveTurn.Summary(appCounts[sid], inpCounts[sid])
			entry.Busy = true
			entry.TurnID = sum.TurnID
			entry.Activity = sum.Activity
			entry.StartedAt = sum.StartedAt
		}
		seen[sid] = entry
	}
	m.mu.Unlock()

	out := make([]SessionSummary, 0, len(seen))
	for _, s := range seen {
		out = append(out, s)
	}
	sort.Slice(out, func(i, j int) bool {
		if out[i].UpdatedEpoch != out[j].UpdatedEpoch {
			return out[i].UpdatedEpoch > out[j].UpdatedEpoch
		}
		return out[i].ID < out[j].ID
	})
	return out, nil
}

func (m *AcpManager) SetModel(ctx context.Context, modelID string) error {
	return m.SetModelForSession(ctx, "", modelID)
}

func (m *AcpManager) SetModelForSession(ctx context.Context, sessionID, modelID string) error {
	modelID = strings.TrimSpace(modelID)
	if modelID == "" {
		return errors.New("model cannot be empty")
	}
	m.mu.Lock()
	resolved := m.resolveModelIDLocked(modelID, "")
	sid := m.resolveSessionIDLocked(sessionID)
	tl := thoughtLevelFromModelID(resolved)
	if sid != "" {
		s := m.getOrCreateSessionLocked(sid)
		s.Model = resolved
		if tl != "" {
			s.ThoughtLevel = tl
		}
	}
	if sid == "" || sid == m.activeSessionID {
		m.currentModel = resolved
		if tl != "" {
			m.thoughtLevel = tl
		}
	}
	m.mu.Unlock()

	emitCfg := func() {
		m.mu.Lock()
		mode := m.currentMode
		curTL := m.thoughtLevel
		if s, ok := m.sessions[sid]; ok {
			mode = s.Mode
			curTL = s.ThoughtLevel
		}
		m.mu.Unlock()
		m.BroadcastHub(StreamEvent{
			Type:      "config_options",
			SessionID: sid,
			Data: map[string]interface{}{
				"session_id":    sid,
				"model":         resolved,
				"mode":          mode,
				"thought_level": curTL,
			},
		})
	}

	if m.mockMode || sid == "" {
		emitCfg()
		return nil
	}
	if err := m.EnsureStarted(ctx); err != nil {
		return err
	}
	_, err := m.callRPC(ctx, "session/set_model", map[string]interface{}{
		"sessionId": sid,
		"modelId":   resolved,
	})
	if err == nil {
		emitCfg()
	}
	return err
}

func (m *AcpManager) SetMode(ctx context.Context, modeID string) error {
	return m.SetModeForSession(ctx, "", modeID)
}

func (m *AcpManager) SetModeForSession(ctx context.Context, sessionID, modeID string) error {
	modeID = strings.TrimSpace(modeID)
	if modeID == "" {
		return errors.New("mode cannot be empty")
	}
	m.mu.Lock()
	sid := m.resolveSessionIDLocked(sessionID)
	if sid != "" {
		s := m.getOrCreateSessionLocked(sid)
		s.Mode = modeID
	}
	if sid == "" || sid == m.activeSessionID {
		m.currentMode = modeID
	}
	m.mu.Unlock()

	emitMode := func() {
		m.BroadcastHub(StreamEvent{
			Type:      "mode",
			SessionID: sid,
			Data:      map[string]interface{}{"session_id": sid, "mode": modeID},
		})
	}

	if m.mockMode || sid == "" {
		emitMode()
		return nil
	}
	if err := m.EnsureStarted(ctx); err != nil {
		return err
	}
	_, err := m.callRPC(ctx, "session/set_mode", map[string]interface{}{
		"sessionId": sid,
		"modeId":    modeID,
	})
	if err == nil {
		emitMode()
	}
	return err
}

func (m *AcpManager) SetThoughtLevel(ctx context.Context, level string) error {
	return m.SetThoughtLevelForSession(ctx, "", level)
}

func (m *AcpManager) SetThoughtLevelForSession(ctx context.Context, sessionID, level string) error {
	level = strings.TrimSpace(level)
	if level == "" {
		return errors.New("thought_level cannot be empty")
	}
	m.mu.Lock()
	sid := m.resolveSessionIDLocked(sessionID)
	if sid != "" {
		s := m.getOrCreateSessionLocked(sid)
		s.ThoughtLevel = level
		if s.Model != "" {
			s.Model = m.resolveModelIDLocked(stripThoughtSuffix(s.Model), level)
		}
	}
	if sid == "" || sid == m.activeSessionID {
		m.thoughtLevel = level
		if m.currentModel != "" {
			m.currentModel = m.resolveModelIDLocked(stripThoughtSuffix(m.currentModel), level)
		}
	}
	m.mu.Unlock()

	emitCfg := func() {
		m.mu.Lock()
		mod := m.currentModel
		mode := m.currentMode
		tl := m.thoughtLevel
		if s, ok := m.sessions[sid]; ok {
			mod = s.Model
			mode = s.Mode
			tl = s.ThoughtLevel
		}
		m.mu.Unlock()
		m.BroadcastHub(StreamEvent{
			Type:      "config_options",
			SessionID: sid,
			Data: map[string]interface{}{
				"session_id":    sid,
				"model":         mod,
				"mode":          mode,
				"thought_level": tl,
			},
		})
	}

	if m.mockMode || sid == "" {
		emitCfg()
		return nil
	}
	if err := m.EnsureStarted(ctx); err != nil {
		return err
	}
	raw, err := m.callRPC(ctx, "session/set_config_option", map[string]interface{}{
		"sessionId": sid,
		"configId":  "thought_level",
		"value":     level,
	})
	if err == nil {
		var res struct {
			ConfigOptions []interface{} `json:"configOptions"`
		}
		if json.Unmarshal(raw, &res) == nil && len(res.ConfigOptions) > 0 {
			m.applyConfigOptionsForSession(sid, res.ConfigOptions)
		}
		emitCfg()
	}
	return err
}

// CancelTurn cancels the active turn for a specific session (or the active session if empty).
func (m *AcpManager) CancelTurn(ctx context.Context) error {
	return m.CancelSessionTurn(ctx, "")
}

func (m *AcpManager) CancelSessionTurn(ctx context.Context, sessionID string) error {
	m.mu.Lock()
	sid := m.resolveSessionIDLocked(sessionID)
	var cancel context.CancelFunc
	var turn *activeTurn
	if s, ok := m.sessions[sid]; ok {
		cancel = s.ActiveCancel
		turn = s.ActiveTurn
	}
	m.mu.Unlock()

	if sid != "" {
		m.cancelPendingInteractiveForSession(sid)
	}

	if turn == nil {
		return nil
	}

	if m.mockMode {
		if cancel != nil {
			cancel()
		}
		return nil
	}

	if sid != "" {
		_ = m.sendNotification("session/cancel", map[string]interface{}{
			"sessionId": sid,
		})
	}

	select {
	case <-turn.doneCh:
		return nil
	case <-time.After(3500 * time.Millisecond):
	case <-ctx.Done():
	}

	if cancel != nil {
		cancel()
	}
	return nil
}

type PromptAttachment struct {
	Type     string `json:"type"`      // "image" or "resource_link"
	MimeType string `json:"mime_type"` // e.g. "image/png"
	Data     string `json:"data"`      // base64 for image
	URI      string `json:"uri"`       // file://... for resource_link
	Name     string `json:"name"`
}

type activeTurn struct {
	id        string
	sessionID string
	startedAt time.Time

	mu               sync.Mutex
	events           []StreamEvent
	seq              int64
	closed           bool
	doneCh           chan struct{}
	subs             map[chan struct{}]struct{}
	onEmit           func(StreamEvent)
	userText         string
	images           int
	text             strings.Builder
	thought          strings.Builder
	tools            []ToolCallRecord
	toolIdx          map[string]int
	activity         string
	hadToolSinceText bool
	emittedContent   bool
}

func newActiveTurn(id, sessionID string, onEmit func(StreamEvent)) *activeTurn {
	return &activeTurn{
		id:        id,
		sessionID: sessionID,
		startedAt: time.Now(),
		doneCh:    make(chan struct{}),
		subs:      make(map[chan struct{}]struct{}),
		onEmit:    onEmit,
		toolIdx:   make(map[string]int),
		activity:  "Thinking",
	}
}

func (t *activeTurn) ID() string {
	return t.id
}

func (t *activeTurn) SessionID() string {
	t.mu.Lock()
	defer t.mu.Unlock()
	return t.sessionID
}

func (t *activeTurn) SetSessionID(sid string) {
	t.mu.Lock()
	t.sessionID = sid
	t.mu.Unlock()
}

func (t *activeTurn) EmittedContent() bool {
	t.mu.Lock()
	defer t.mu.Unlock()
	return t.emittedContent
}

func (t *activeTurn) Snapshot() ActiveTurnSnapshot {
	t.mu.Lock()
	defer t.mu.Unlock()
	toolsCopy := make([]ToolCallRecord, len(t.tools))
	copy(toolsCopy, t.tools)
	return ActiveTurnSnapshot{
		TurnID:    t.id,
		SessionID: t.sessionID,
		StartedAt: t.startedAt.UnixMilli(),
		Seq:       t.seq,
		Activity:  t.activity,
		UserText:  t.userText,
		Images:    t.images,
		Text:      t.text.String(),
		Thought:   t.thought.String(),
		Tools:     toolsCopy,
	}
}

func (t *activeTurn) Summary(pendingApprovals, pendingInputs int) ActiveTurnSummary {
	t.mu.Lock()
	defer t.mu.Unlock()
	act := t.activity
	if pendingApprovals > 0 {
		act = "Needs approval"
	} else if pendingInputs > 0 {
		act = "Waiting for input"
	}
	return ActiveTurnSummary{
		TurnID:           t.id,
		SessionID:        t.sessionID,
		StartedAt:        t.startedAt.UnixMilli(),
		Activity:         act,
		Seq:              t.seq,
		PendingApprovals: pendingApprovals,
		PendingInputs:    pendingInputs,
	}
}

func compactActivityLabel(s string, maxChars int) string {
	s = strings.TrimSpace(strings.ReplaceAll(s, "\n", " "))
	if s == "" {
		return "Working"
	}
	if len(s) > maxChars {
		return strings.TrimSpace(s[:maxChars]) + "…"
	}
	return s
}

func (t *activeTurn) emit(ev StreamEvent) {
	t.mu.Lock()
	if t.closed {
		t.mu.Unlock()
		return
	}
	t.seq++
	ev.Seq = t.seq
	ev.TurnID = t.id
	if t.sessionID != "" {
		ev.SessionID = t.sessionID
	}
	if ev.Data == nil {
		ev.Data = map[string]interface{}{}
	}
	ev.Data["turn_id"] = t.id
	ev.Data["seq"] = ev.Seq
	if t.sessionID != "" {
		ev.Data["session_id"] = t.sessionID
	}

	// Maintain live turn snapshot atomically across all event sources
	switch ev.Type {
	case "start":
		if ut, ok := ev.Data["user_text"].(string); ok {
			t.userText = ut
		}
		if imgs, ok := toInt(ev.Data["images"]); ok {
			t.images = imgs
		}
		t.activity = "Thinking"
	case "thought":
		if txt, ok := ev.Data["text"].(string); ok && txt != "" {
			t.thought.WriteString(txt)
			t.emittedContent = true
			t.activity = "Thinking"
		}
	case "delta":
		if txt, ok := ev.Data["text"].(string); ok && txt != "" {
			if t.hadToolSinceText && t.text.Len() > 0 {
				existing := t.text.String()
				if !strings.HasSuffix(existing, "\n") && !strings.HasPrefix(txt, "\n") {
					sep := "\n\n"
					t.text.WriteString(sep)
					ev.Data["text"] = sep + txt
				}
			}
			t.hadToolSinceText = false
			t.text.WriteString(txt)
			t.emittedContent = true
			t.activity = "Writing response"
		}
	case "tool":
		t.hadToolSinceText = true
		t.emittedContent = true
		tcID, _ := ev.Data["id"].(string)
		name, _ := ev.Data["name"].(string)
		title, _ := ev.Data["title"].(string)
		kind, _ := ev.Data["kind"].(string)
		status, _ := ev.Data["status"].(string)
		rec := ToolCallRecord{
			ID:        tcID,
			Name:      name,
			Title:     title,
			Kind:      kind,
			Status:    status,
			Args:      ev.Data["args"],
			Locations: ev.Data["locations"],
		}
		if idx, exists := t.toolIdx[tcID]; exists && tcID != "" {
			t.tools[idx] = rec
		} else {
			if tcID != "" {
				t.toolIdx[tcID] = len(t.tools)
			}
			t.tools = append(t.tools, rec)
		}
		lbl := title
		if lbl == "" {
			lbl = name
		}
		t.activity = compactActivityLabel(lbl, 48)
	case "result":
		tcID, _ := ev.Data["id"].(string)
		name, _ := ev.Data["name"].(string)
		title, _ := ev.Data["title"].(string)
		kind, _ := ev.Data["kind"].(string)
		output, _ := ev.Data["output"].(string)
		status, _ := ev.Data["status"].(string)
		isErr, _ := ev.Data["is_error"].(bool)
		if idx, exists := t.toolIdx[tcID]; exists && tcID != "" {
			if output != "" {
				t.tools[idx].Output = output
			}
			if status != "" {
				t.tools[idx].Status = status
			}
			if title != "" {
				t.tools[idx].Title = title
			}
			t.tools[idx].IsError = isErr
		} else if tcID != "" {
			t.toolIdx[tcID] = len(t.tools)
			t.tools = append(t.tools, ToolCallRecord{
				ID:      tcID,
				Name:    name,
				Title:   title,
				Kind:    kind,
				Status:  status,
				Args:    ev.Data["args"],
				Output:  output,
				IsError: isErr,
			})
		}
	case "approval":
		t.activity = "Needs approval"
	case "prompt":
		t.activity = "Waiting for input"
	case "approval_resolved", "input_resolved":
		t.activity = "Working"
	case "message":
		if txt, ok := ev.Data["text"].(string); ok && txt != "" && t.text.Len() == 0 {
			t.text.WriteString(txt)
		}
		if th, ok := ev.Data["thought"].(string); ok && th != "" && t.thought.Len() == 0 {
			t.thought.WriteString(th)
		}
	}

	t.events = append(t.events, ev)
	for ch := range t.subs {
		select {
		case ch <- struct{}{}:
		default:
		}
	}
	cb := t.onEmit
	t.mu.Unlock()

	if cb != nil {
		cb(ev)
	}
}

func (t *activeTurn) close() {
	t.mu.Lock()
	if !t.closed {
		t.closed = true
		close(t.doneCh)
		for ch := range t.subs {
			select {
			case ch <- struct{}{}:
			default:
			}
		}
	}
	t.mu.Unlock()
}

func (t *activeTurn) EventsAfter(afterSeq int64) []StreamEvent {
	t.mu.Lock()
	defer t.mu.Unlock()
	if afterSeq < 0 {
		afterSeq = 0
	}
	if int(afterSeq) >= len(t.events) {
		return nil
	}
	out := make([]StreamEvent, len(t.events)-int(afterSeq))
	copy(out, t.events[afterSeq:])
	return out
}

func (t *activeTurn) subscribe(ctx context.Context, afterSeq int64, onEvent func(StreamEvent)) {
	notify := make(chan struct{}, 1)
	t.mu.Lock()
	t.subs[notify] = struct{}{}
	t.mu.Unlock()

	defer func() {
		t.mu.Lock()
		delete(t.subs, notify)
		t.mu.Unlock()
	}()

	idx := int(afterSeq)
	if idx < 0 {
		idx = 0
	}
	for {
		t.mu.Lock()
		var batch []StreamEvent
		if idx < len(t.events) {
			batch = append(batch, t.events[idx:]...)
			idx = len(t.events)
		}
		closed := t.closed
		t.mu.Unlock()

		for _, ev := range batch {
			if ctx.Err() != nil {
				return
			}
			onEvent(ev)
		}

		if closed {
			return
		}

		select {
		case <-ctx.Done():
			return
		case <-notify:
		}
	}
}

func (m *AcpManager) CurrentTurn() *activeTurn {
	return m.ActiveTurnForSession("")
}

func (m *AcpManager) ActiveTurnForSession(sessionID string) *activeTurn {
	m.mu.Lock()
	defer m.mu.Unlock()
	sid := m.resolveSessionIDLocked(sessionID)
	if s, ok := m.sessions[sid]; ok {
		return s.ActiveTurn
	}
	return nil
}

func (m *AcpManager) StreamPrompt(ctx context.Context, text string, attachments []PromptAttachment, onEvent func(StreamEvent)) error {
	turn, err := m.StartPrompt(text, attachments)
	if err != nil {
		return err
	}
	turn.subscribe(ctx, 0, onEvent)
	return nil
}

func (m *AcpManager) StartLocalShellTurn(cmdLine string) (*activeTurn, error) {
	return m.StartLocalShellTurnForSession("", cmdLine)
}

func (m *AcpManager) StartLocalShellTurnForSession(sessionID, cmdLine string) (*activeTurn, error) {
	if err := m.EnsureStarted(context.Background()); err != nil {
		return nil, err
	}

	m.mu.Lock()
	sid := m.resolveSessionIDLocked(sessionID)
	if sid == "" {
		m.mu.Unlock()
		var err error
		sid, err = m.NewSession(context.Background(), "")
		if err != nil {
			return nil, err
		}
		m.mu.Lock()
	}
	sess := m.getOrCreateSessionLocked(sid)
	if sess.ActiveTurn != nil {
		m.mu.Unlock()
		return nil, errors.New("conversation is busy")
	}
	cwd := sess.Cwd
	if cwd == "" {
		cwd = m.cwd
	}
	turnCtx, turnCancel := context.WithCancel(context.Background())
	turnID := fmt.Sprintf("turn-%d", m.nextTurnSeq.Add(1))
	turn := newActiveTurn(turnID, sid, m.BroadcastHub)
	sess.ActiveTurn = turn
	sess.ActiveCancel = turnCancel
	m.mu.Unlock()

	m.BroadcastSessionsActivity("turn_started")

	go func() {
		defer func() {
			turnCancel()
			turn.close()
			m.mu.Lock()
			if s, ok := m.sessions[sid]; ok && s.ActiveTurn == turn {
				s.ActiveTurn = nil
				s.ActiveCancel = nil
				s.LastCompletedTurnID = turnID
			}
			m.mu.Unlock()
			m.BroadcastSessionsActivity("turn_finished")
		}()

		turn.emit(StreamEvent{
			Type: "start",
			Data: map[string]interface{}{
				"session_id": sid,
				"user_text":  "!" + cmdLine,
			},
		})
		tcID := fmt.Sprintf("shell-%d", time.Now().UnixNano())
		turn.emit(StreamEvent{
			Type: "tool",
			Data: map[string]interface{}{
				"id":     tcID,
				"name":   "shell",
				"title":  "$ " + cmdLine,
				"kind":   "execute",
				"status": "running",
				"args":   map[string]interface{}{"command": cmdLine, "cwd": cwd},
			},
		})
		out, exitCode, _ := m.RunLocalShellForSession(turnCtx, sid, cwd, cmdLine)
		status := "completed"
		if exitCode != 0 {
			status = "error"
		}
		turn.emit(StreamEvent{
			Type: "result",
			Data: map[string]interface{}{
				"id":       tcID,
				"name":     "shell",
				"title":    "$ " + cmdLine,
				"status":   status,
				"output":   out,
				"is_error": exitCode != 0,
			},
		})
		formatted := fmt.Sprintf("```console\n$ %s\n%s\n```", cmdLine, strings.TrimRight(out, "\n"))
		turn.emit(StreamEvent{Type: "delta", Data: map[string]interface{}{"text": formatted}})
		turn.emit(StreamEvent{Type: "message", Data: map[string]interface{}{"text": formatted}})
		turn.emit(StreamEvent{Type: "done", Data: map[string]interface{}{"session_id": sid, "stop_reason": "end_turn"}})
	}()

	return turn, nil
}

func (m *AcpManager) StartPrompt(text string, attachments []PromptAttachment) (*activeTurn, error) {
	return m.StartPromptForSession("", text, attachments)
}

func (m *AcpManager) StartPromptForSession(sessionID, text string, attachments []PromptAttachment) (*activeTurn, error) {
	if err := m.EnsureStarted(context.Background()); err != nil {
		return nil, err
	}

	m.mu.Lock()
	sid := m.resolveSessionIDLocked(sessionID)
	m.mu.Unlock()

	if sid == "" {
		var err error
		sid, err = m.NewSession(context.Background(), "")
		if err != nil {
			return nil, err
		}
	}

	m.mu.Lock()
	sess := m.getOrCreateSessionLocked(sid)
	if sess.ActiveTurn != nil {
		m.mu.Unlock()
		return nil, errors.New("conversation is busy")
	}
	cwd := sess.Cwd
	if cwd == "" {
		cwd = m.cwd
	}
	loaded := sess.Loaded && !sess.NeedLoad
	turnCtx, turnCancel := context.WithCancel(context.Background())
	turnID := fmt.Sprintf("turn-%d", m.nextTurnSeq.Add(1))
	turn := newActiveTurn(turnID, sid, m.BroadcastHub)
	sess.ActiveTurn = turn
	sess.ActiveCancel = turnCancel
	m.mu.Unlock()

	m.BroadcastSessionsActivity("turn_started")

	go m.runPromptTurn(turnCtx, turnCancel, turn, sid, cwd, loaded, text, attachments)
	return turn, nil
}

func (m *AcpManager) runPromptTurn(turnCtx context.Context, turnCancel context.CancelFunc, turn *activeTurn, sid, cwd string, loaded bool, text string, attachments []PromptAttachment) {
	onEvent := turn.emit
	var streamRegID int64

	defer func() {
		if streamRegID != 0 {
			m.unregisterSessionStream(sid, streamRegID)
		}
		turnCancel()
		turn.close()
		m.mu.Lock()
		if s, ok := m.sessions[sid]; ok && s.ActiveTurn == turn {
			s.ActiveTurn = nil
			s.ActiveCancel = nil
			s.LastCompletedTurnID = turn.ID()
		}
		m.mu.Unlock()
		m.BroadcastSessionsActivity("turn_finished")
	}()

	if !loaded && !m.mockMode {
		// Load/resume this session in ACP before sending session/prompt
		if err := m.ensureSessionLoadedForPrompt(turnCtx, sid, cwd); err != nil {
			onEvent(StreamEvent{
				Type: "error",
				Data: map[string]interface{}{"message": "Failed to open session: " + err.Error()},
			})
			return
		}
	}

	// Record user message in session cache
	nowISO := time.Now().UTC().Format(time.RFC3339)
	imgCount := 0
	for _, a := range attachments {
		if a.Type == "image" {
			imgCount++
		}
	}
	m.mu.Lock()
	sess := m.getOrCreateSessionLocked(sid)
	sess.Messages = append(sess.Messages, ChatMessage{
		Role:      "user",
		Text:      text,
		Timestamp: nowISO,
		Images:    imgCount,
	})
	sess.UpdatedAt = time.Now()
	if sess.Title == "" || sess.Title == "New conversation" || strings.HasPrefix(sess.Title, "Conversation ") {
		firstLine := strings.TrimSpace(strings.Split(text, "\n")[0])
		if len(firstLine) > 60 {
			firstLine = firstLine[:60] + "…"
		}
		if firstLine != "" {
			sess.Title = firstLine
			if m.activeSessionID == sid {
				m.activeTitle = firstLine
			}
		}
	}
	curModel := sess.Model
	if curModel == "" {
		curModel = m.currentModel
	}
	curMode := sess.Mode
	if curMode == "" {
		curMode = m.currentMode
	}
	titleSnap := sess.Title
	m.mu.Unlock()

	onEvent(StreamEvent{
		Type: "start",
		Data: map[string]interface{}{
			"session_id": sid,
			"title":      titleSnap,
			"model":      curModel,
			"mode":       curMode,
			"user_text":  text,
			"images":     imgCount,
		},
	})

	if m.mockMode {
		_ = m.runMockPrompt(turnCtx, sid, text, attachments, onEvent)
		return
	}

	streamRegID = m.registerSessionStream(sid, func(ev StreamEvent) {
		onEvent(ev)
	})

	promptParts := make([]map[string]interface{}, 0, 1+len(attachments))
	for _, a := range attachments {
		switch a.Type {
		case "image":
			if a.Data != "" {
				mime := a.MimeType
				if mime == "" {
					mime = "image/png"
				}
				promptParts = append(promptParts, map[string]interface{}{
					"type":     "image",
					"data":     a.Data,
					"mimeType": mime,
				})
			}
		case "resource_link":
			if a.URI != "" {
				promptParts = append(promptParts, map[string]interface{}{
					"type": "resource_link",
					"uri":  a.URI,
					"name": a.Name,
				})
			}
		}
	}
	if text != "" || len(promptParts) == 0 {
		promptParts = append(promptParts, map[string]interface{}{
			"type": "text",
			"text": text,
		})
	}

	raw, err := m.callRPC(turnCtx, "session/prompt", map[string]interface{}{
		"sessionId": sid,
		"prompt":    promptParts,
	})

	// Auto-recover once if ACP subprocess died before emitting any content
	if err != nil && !turn.EmittedContent() && isTransportError(err) && turnCtx.Err() == nil {
		if rerr := m.EnsureStarted(turnCtx); rerr == nil {
			if oerr := m.ensureSessionLoadedForPrompt(turnCtx, sid, cwd); oerr == nil {
				raw, err = m.callRPC(turnCtx, "session/prompt", map[string]interface{}{
					"sessionId": sid,
					"prompt":    promptParts,
				})
			}
		}
	}

	if err != nil {
		snap := turn.Snapshot()
		if snap.Text != "" || snap.Thought != "" || len(snap.Tools) > 0 {
			m.mu.Lock()
			s := m.getOrCreateSessionLocked(sid)
			s.Messages = append(s.Messages, ChatMessage{
				Role:      "assistant",
				Text:      snap.Text,
				Thought:   snap.Thought,
				Tools:     snap.Tools,
				Timestamp: time.Now().UTC().Format(time.RFC3339),
			})
			s.UpdatedAt = time.Now()
			m.mu.Unlock()
		}

		if errors.Is(err, context.Canceled) {
			onEvent(StreamEvent{
				Type: "cancelled",
				Data: map[string]interface{}{"reason": "cancelled"},
			})
			onEvent(StreamEvent{
				Type: "done",
				Data: map[string]interface{}{"session_id": sid, "stop_reason": "cancelled"},
			})
			return
		}
		onEvent(StreamEvent{
			Type: "error",
			Data: map[string]interface{}{"message": err.Error()},
		})
		return
	}

	var promptRes struct {
		StopReason string `json:"stopReason"`
		Usage      struct {
			InputTokens       int64 `json:"inputTokens"`
			OutputTokens      int64 `json:"outputTokens"`
			CachedReadTokens  int64 `json:"cachedReadTokens"`
			CachedWriteTokens int64 `json:"cachedWriteTokens"`
			ThoughtTokens     int64 `json:"thoughtTokens"`
			TotalTokens       int64 `json:"totalTokens"`
		} `json:"usage"`
	}
	_ = json.Unmarshal(raw, &promptRes)

	snap := turn.Snapshot()

	m.mu.Lock()
	s := m.getOrCreateSessionLocked(sid)
	if snap.Text != "" || snap.Thought != "" || len(snap.Tools) > 0 {
		s.Messages = append(s.Messages, ChatMessage{
			Role:      "assistant",
			Text:      snap.Text,
			Thought:   snap.Thought,
			Tools:     snap.Tools,
			Timestamp: time.Now().UTC().Format(time.RFC3339),
		})
	}
	s.UpdatedAt = time.Now()
	s.Usage.InputTokens += promptRes.Usage.InputTokens
	s.Usage.OutputTokens += promptRes.Usage.OutputTokens
	s.Usage.CachedReadTokens += promptRes.Usage.CachedReadTokens
	s.Usage.CachedWriteTokens += promptRes.Usage.CachedWriteTokens
	s.Usage.ThoughtTokens += promptRes.Usage.ThoughtTokens
	s.Usage.TotalTokens += promptRes.Usage.TotalTokens
	s.Usage.Turns++
	usageSnap := s.Usage
	titleSnap = s.Title
	m.mu.Unlock()

	m.refreshDiskSig(sid)

	onEvent(StreamEvent{
		Type: "message",
		Data: map[string]interface{}{
			"text":    snap.Text,
			"thought": snap.Thought,
		},
	})
	onEvent(StreamEvent{
		Type: "usage",
		Data: map[string]interface{}{
			"session_id":          sid,
			"input_tokens":        usageSnap.InputTokens,
			"output_tokens":       usageSnap.OutputTokens,
			"cached_read_tokens":  usageSnap.CachedReadTokens,
			"cached_write_tokens": usageSnap.CachedWriteTokens,
			"thought_tokens":      usageSnap.ThoughtTokens,
			"total_tokens":        usageSnap.TotalTokens,
			"turns":               usageSnap.Turns,
		},
	})
	if promptRes.StopReason == "cancelled" {
		onEvent(StreamEvent{
			Type: "cancelled",
			Data: map[string]interface{}{"reason": "cancelled"},
		})
	}
	onEvent(StreamEvent{
		Type: "done",
		Data: map[string]interface{}{
			"session_id":  sid,
			"title":       titleSnap,
			"stop_reason": promptRes.StopReason,
		},
	})
}

func (m *AcpManager) ensureSessionLoadedForPrompt(ctx context.Context, sessionID, cwd string) error {
	if err := m.EnsureStarted(ctx); err != nil {
		return err
	}
	m.mu.Lock()
	sess := m.getOrCreateSessionLocked(sessionID)
	needReload := sess.NeedLoad
	alreadyLoaded := sess.Loaded
	m.mu.Unlock()

	if alreadyLoaded && !needReload {
		return nil
	}
	if alreadyLoaded && needReload {
		_, _ = m.callRPC(ctx, "session/close", map[string]interface{}{"sessionId": sessionID})
	}
	raw, err := m.callRPC(ctx, "session/resume", map[string]interface{}{
		"sessionId":  sessionID,
		"cwd":        cwd,
		"mcpServers": []interface{}{},
	})
	if err != nil {
		// Fallback to session/load
		raw, err = m.callRPC(ctx, "session/load", map[string]interface{}{
			"sessionId":  sessionID,
			"cwd":        cwd,
			"mcpServers": []interface{}{},
		})
	}
	if err != nil {
		return err
	}
	m.applySessionResponse(raw, sessionID)
	m.mu.Lock()
	if s, ok := m.sessions[sessionID]; ok {
		s.Loaded = true
		s.NeedLoad = false
	}
	m.mu.Unlock()
	return nil
}

func (m *AcpManager) runMockPrompt(ctx context.Context, sid, text string, attachments []PromptAttachment, onEvent func(StreamEvent)) error {
	lower := strings.ToLower(strings.TrimSpace(text))

	m.mu.Lock()
	sess := m.getOrCreateSessionLocked(sid)
	cwd := sess.Cwd
	model := sess.Model
	mode := sess.Mode
	m.mu.Unlock()

	if strings.Contains(lower, "slow") {
		onEvent(StreamEvent{Type: "thought", Data: map[string]interface{}{"text": "Thinking carefully about the request..."}})
		var acc strings.Builder
		for i := 0; i < 20; i++ {
			select {
			case <-ctx.Done():
				if acc.Len() > 0 {
					m.appendMockAssistant(sid, acc.String(), "Thinking carefully about the request...", nil)
				}
				onEvent(StreamEvent{Type: "cancelled", Data: map[string]interface{}{"reason": "cancelled"}})
				onEvent(StreamEvent{Type: "done", Data: map[string]interface{}{"session_id": sid, "stop_reason": "cancelled"}})
				return nil
			case <-time.After(100 * time.Millisecond):
				chunk := fmt.Sprintf("chunk %d ", i+1)
				acc.WriteString(chunk)
				onEvent(StreamEvent{Type: "delta", Data: map[string]interface{}{"text": chunk}})
			}
		}
		reply := acc.String()
		m.appendMockAssistant(sid, reply, "Thinking carefully about the request...", nil)
		onEvent(StreamEvent{Type: "message", Data: map[string]interface{}{"text": reply, "thought": "Thinking carefully about the request..."}})
		onEvent(StreamEvent{Type: "done", Data: map[string]interface{}{"session_id": sid, "stop_reason": "end_turn"}})
		return nil
	}

	if strings.Contains(lower, "need approval") || strings.Contains(lower, "approve") {
		permID := fmt.Sprintf("perm-mock-%s", shortID(sid))
		pa := &PendingApproval{
			ID:           permID,
			SessionID:    sid,
			SessionTitle: m.sessionTitleByID(sid),
			Tool:         "run_command",
			Title:        "Run command: echo approved",
			Kind:         "execute",
			Args:         map[string]interface{}{"CommandLine": "echo approved"},
			Options: []map[string]interface{}{
				{"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"},
				{"optionId": "allow_always", "name": "Always allow", "kind": "allow_always"},
				{"optionId": "reject_once", "name": "Reject", "kind": "reject_once"},
			},
			ReplyCh: make(chan string, 1),
		}
		m.interactiveMu.Lock()
		m.approvals[pa.ID] = pa
		m.interactiveMu.Unlock()

		onEvent(StreamEvent{
			Type: "approval",
			Data: map[string]interface{}{
				"id":            pa.ID,
				"session_id":    pa.SessionID,
				"session_title": pa.SessionTitle,
				"tool":          pa.Tool,
				"title":         pa.Title,
				"kind":          pa.Kind,
				"args":          pa.Args,
				"options":       pa.Options,
				"summary":       pa.Title,
			},
		})
		m.BroadcastSessionsActivity("approval_requested")

		var choice string
		select {
		case <-ctx.Done():
			choice = "cancelled"
		case choice = <-pa.ReplyCh:
		}
		m.interactiveMu.Lock()
		delete(m.approvals, pa.ID)
		m.interactiveMu.Unlock()
		m.BroadcastSessionsActivity("approval_resolved")

		if strings.HasPrefix(choice, "reject") || choice == "cancelled" {
			reply := "Command execution was denied by user."
			m.appendMockAssistant(sid, reply, "", nil)
			onEvent(StreamEvent{Type: "delta", Data: map[string]interface{}{"text": reply}})
			onEvent(StreamEvent{Type: "message", Data: map[string]interface{}{"text": reply}})
			onEvent(StreamEvent{Type: "done", Data: map[string]interface{}{"session_id": sid, "stop_reason": "end_turn"}})
			return nil
		}
	}

	thought := "Analyzing request in workspace `" + cwd + "` using model `" + model + "`."
	onEvent(StreamEvent{
		Type: "thought",
		Data: map[string]interface{}{"text": thought},
	})

	tcID := "tc-mock-1"
	toolArgs := map[string]interface{}{"Path": filepath.Join(cwd, "README.md")}
	onEvent(StreamEvent{
		Type: "tool",
		Data: map[string]interface{}{
			"id":     tcID,
			"name":   "read_file",
			"title":  "Read README.md",
			"kind":   "read",
			"status": "running",
			"args":   toolArgs,
		},
	})
	toolOut := "Gravitas workspace verified."
	onEvent(StreamEvent{
		Type: "result",
		Data: map[string]interface{}{
			"id":       tcID,
			"name":     "read_file",
			"title":    "Read README.md",
			"status":   "completed",
			"output":   toolOut,
			"is_error": false,
		},
	})

	reply := fmt.Sprintf("Here is the response for **%s**:\n\n- Model: `%s`\n- Mode: `%s`\n\n```go\nfmt.Println(\"Gravitas Ready\")\n```", text, model, mode)
	onEvent(StreamEvent{
		Type: "delta",
		Data: map[string]interface{}{"text": reply},
	})

	tools := []ToolCallRecord{
		{
			ID:     tcID,
			Name:   "read_file",
			Title:  "Read README.md",
			Kind:   "read",
			Status: "completed",
			Args:   toolArgs,
			Output: toolOut,
		},
	}
	m.appendMockAssistant(sid, reply, thought, tools)

	m.mu.Lock()
	s := m.getOrCreateSessionLocked(sid)
	s.Usage.InputTokens += 120
	s.Usage.OutputTokens += 65
	s.Usage.ThoughtTokens += 25
	s.Usage.TotalTokens += 210
	s.Usage.Turns++
	s.ContextUsage = ContextUsage{Used: s.Usage.TotalTokens, Size: 1048576}
	usageSnap := s.Usage
	ctxSnap := s.ContextUsage
	titleSnap := s.Title
	m.mu.Unlock()

	onEvent(StreamEvent{
		Type: "message",
		Data: map[string]interface{}{
			"text":    reply,
			"thought": thought,
		},
	})
	onEvent(StreamEvent{
		Type: "context_usage",
		Data: map[string]interface{}{
			"session_id": sid,
			"used":       ctxSnap.Used,
			"size":       ctxSnap.Size,
		},
	})
	onEvent(StreamEvent{
		Type: "usage",
		Data: map[string]interface{}{
			"session_id":     sid,
			"input_tokens":   usageSnap.InputTokens,
			"output_tokens":  usageSnap.OutputTokens,
			"thought_tokens": usageSnap.ThoughtTokens,
			"total_tokens":   usageSnap.TotalTokens,
			"turns":          usageSnap.Turns,
		},
	})
	onEvent(StreamEvent{
		Type: "done",
		Data: map[string]interface{}{
			"session_id":  sid,
			"title":       titleSnap,
			"stop_reason": "end_turn",
		},
	})
	return nil
}

func (m *AcpManager) appendMockAssistant(sid, text, thought string, tools []ToolCallRecord) {
	m.mu.Lock()
	defer m.mu.Unlock()
	s := m.getOrCreateSessionLocked(sid)
	s.Messages = append(s.Messages, ChatMessage{
		Role:      "assistant",
		Text:      text,
		Thought:   thought,
		Tools:     tools,
		Timestamp: time.Now().UTC().Format(time.RFC3339),
	})
	s.UpdatedAt = time.Now()
}

func shortID(id string) string {
	if len(id) <= 8 {
		return id
	}
	return id[:8]
}