package server import ( "context" "errors" "log" "strings" "sync" "time" "git.a-wan.net/alan/pipelines/internal/opencode" "git.a-wan.net/alan/pipelines/internal/protocol" ) // chatPermissionPollInterval is the fixed interval between permission polls: one // GET per poll through the shared Connection bounds, never a busy loop. The first // poll runs immediately so a request pending when the prompt is sent is surfaced // without waiting a full interval. const chatPermissionPollInterval = 2 * time.Second func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) { if broker == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) return } prompt := request.ChatPrompt if prompt == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat prompt payload is required"}) return } if !opencode.ValidSessionID(prompt.SessionID) { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"}) return } if strings.TrimSpace(prompt.Text) == "" { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a nonempty chat prompt is required"}) return } // Reject an oversized prompt before any OpenCode call; the bound matches the // OpenCode request limit. if len(prompt.Text) > opencode.MaxRequest { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat prompt exceeds 64 KiB"}) return } // Claim the session before subscribing or prompting: a second client must be // rejected here, before any broker call, so two clients cannot silently write // the same conversation. The same client may re-prompt its own session. sessionID := prompt.SessionID if !hub.claim(sessionID, clientID) { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is busy with another client"}) return } // Subscribe to the OpenCode firehose before posting the prompt: the stream // has no replay cursor (research 2.4), so a delta emitted between the POST // and the subscription would otherwise be lost. Frames that arrive before the // ack is written are buffered and flushed in order after it. streamCtx, streamCancel := context.WithCancel(ctx) attached := make(chan struct{}) var attachOnce sync.Once streamResult := make(chan error, 1) var bufferMu sync.Mutex buffering := true var buffered []protocol.ChatEventFrame go func() { streamResult <- broker.Stream(streamCtx, sessionID, func() { attachOnce.Do(func() { close(attached) }) }, func(frame protocol.ChatEventFrame) error { bufferMu.Lock() if buffering { buffered = append(buffered, frame) bufferMu.Unlock() return nil } bufferMu.Unlock() hub.apply(frame) return write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}) }) }() select { case <-attached: case err := <-streamResult: streamCancel() hub.release(sessionID, clientID) if err != nil && ctx.Err() == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat stream: " + err.Error()}) } return case <-ctx.Done(): streamCancel() hub.release(sessionID, clientID) return } if err := broker.Prompt(ctx, sessionID, prompt.Text); err != nil { streamCancel() hub.release(sessionID, clientID) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } // Recency is one UPDATE: it moves the operator session to the front of // chat_sessions. A session id that is not an operator session updates no row // and is not an error, so pipeline stage prompts are unaffected. if registry != nil { if err := registry.TouchOperatorSession(ctx, sessionID); err != nil { log.Printf("touch operator session %s: %v", sessionID, err) } } // Acknowledge the accepted prompt with the echoed request id, then stream the // reply. The prompt is sent exactly once and never re-sent on resume. if err := write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID}); err != nil { streamCancel() hub.release(sessionID, clientID) return } // Flush frames buffered while the prompt was accepted, then resume live // delivery. Holding bufferMu preserves order: the stream goroutine either // buffered before this flush or waits and writes after it. bufferMu.Lock() buffering = false pending := buffered buffered = nil for _, frame := range pending { hub.apply(frame) if err := write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}); err != nil { bufferMu.Unlock() streamCancel() hub.release(sessionID, clientID) return } } bufferMu.Unlock() go drainChatStream(ctx, streamResult, streamCancel, hub, sessionID, clientID, write) // Poll for pending approval requests alongside the event stream, sharing // streamCtx so the poller stops when the stream ends or the client // disconnects. The first poll runs immediately. go pollChatPermissions(streamCtx, broker, hub, sessionID, write) } // pollChatPermissions polls the broker's pending-approval list on a fixed // interval, sharing the chat subscription's context so it stops on disconnect or // when the turn's stream ends. The hub dedups the request ids, so each pending // request is pushed at most once; a poll failure is surfaced once through the // same write closure instead of staying silent. A backend that does not expose // the approval surface (opencode.ErrPermissionUnsupported) stops the poller // quietly, so the documented limitation is not reported as a per-prompt error. func pollChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) { ticker := time.NewTicker(chatPermissionPollInterval) defer ticker.Stop() reported := false for { if err := pushChatPermissions(ctx, broker, hub, sessionID, write); err != nil { if ctx.Err() != nil { return } if errors.Is(err, opencode.ErrPermissionUnsupported) { log.Printf("chat permission poll session=%s: %v", sessionID, err) return } if reported { log.Printf("chat permission poll session=%s: %v", sessionID, err) } else { reported = true _ = write(protocol.Message{Type: protocol.Error, Error: "chat permission poll: " + err.Error()}) } } select { case <-ctx.Done(): return case <-ticker.C: } } } // pushChatPermissions performs one poll and writes a chat_permission frame for // every newly seen request of the session, through the same connection-scoped // write closure as the chat stream. It never re-pushes a request id, and releases // the reservation on a write failure so the frame is not silently dropped. func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) error { pending, err := broker.Permissions(ctx, sessionID) if err != nil { return err } for _, request := range pending { if request.SessionID != sessionID || request.RequestID == "" { continue } if !hub.seenPermission(sessionID, request.RequestID) { continue } frame := request if err := write(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}); err != nil { hub.forgetPermission(sessionID, request.RequestID) return err } } return nil } // drainChatStream reports the terminal error of a chat subscription and releases // its context and the session claim once the stream has ended, so a later client // is no longer blocked and nothing leaks. func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, hub *chatHub, sessionID, clientID string, write func(protocol.Message) error) { defer cancel() defer hub.release(sessionID, clientID) if err := <-result; err != nil && ctx.Err() == nil { log.Printf("chat stream session=%s: %v", sessionID, err) _ = write(protocol.Message{Type: protocol.Error, Error: "chat stream: " + err.Error()}) } }