chat: deliver attachments and cancel runs immediately
Carry browser files as base64 prompt attachments, write them to private temporary files and pass file:// references to OpenCode, and map the user turn's top-level files back into history. Replay a running step on subscribe, forward only a caller-supplied msg_ id, and persist cancel on the run and live step before interrupting the runner.
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
@@ -47,6 +48,13 @@ type chatPromptWithMessageID interface {
|
||||
PromptWithMessageID(context.Context, string, string, string) error
|
||||
}
|
||||
|
||||
// chatPromptWithFiles is implemented by a broker that can hand local files to
|
||||
// the agent with a prompt. The server writes browser attachment bytes to private
|
||||
// temporary files first; a browser URI is not readable by the agent service.
|
||||
type chatPromptWithFiles interface {
|
||||
PromptWithMessageIDFiles(context.Context, string, string, string, []opencode.PromptFile) error
|
||||
}
|
||||
|
||||
// chatAnswerer is the optional form-answer surface. Test brokers and older
|
||||
// backends need not implement it; a broker that does not answers chat_answer
|
||||
// with a clear error rather than pretending the question was delivered.
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxChatAttachments bounds one prompt's browser files. OpenCode receives a
|
||||
// small number of local files; more is not a useful chat message.
|
||||
maxChatAttachments = 8
|
||||
// maxChatAttachmentBytes bounds the decoded bytes for one prompt. The browser
|
||||
// sends base64 over the existing 2 MiB websocket frame, so this keeps the
|
||||
// encoded body comfortably below that hard limit.
|
||||
maxChatAttachmentBytes = 1 << 20
|
||||
)
|
||||
|
||||
// prepareChatAttachments writes browser attachment bytes into a private
|
||||
// temporary directory and returns the file references OpenCode accepts plus the
|
||||
// display parts the user turn carries. A browser File reference is not readable
|
||||
// by the agent service, so the bytes must cross the websocket.
|
||||
func prepareChatAttachments(sessionID string, attachments []protocol.ChatAttachment) ([]opencode.PromptFile, []protocol.ChatPart, error) {
|
||||
if len(attachments) == 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
if len(attachments) > maxChatAttachments {
|
||||
return nil, nil, fmt.Errorf("at most %d attachments are allowed", maxChatAttachments)
|
||||
}
|
||||
dir := filepath.Join(os.TempDir(), "pipelines-chat-attachments", safeChatAttachmentSegment(sessionID))
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, nil, fmt.Errorf("prepare attachment directory: %w", err)
|
||||
}
|
||||
var files []opencode.PromptFile
|
||||
var parts []protocol.ChatPart
|
||||
var created []string
|
||||
cleanup := func() {
|
||||
for _, path := range created {
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
}
|
||||
total := 0
|
||||
for index, attachment := range attachments {
|
||||
data := strings.TrimSpace(attachment.Data)
|
||||
if data == "" {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("attachment %q has no data", attachment.Name)
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(data)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("attachment %q is not valid base64", attachment.Name)
|
||||
}
|
||||
total += len(decoded)
|
||||
if total > maxChatAttachmentBytes {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("attachments exceed the %s limit", "1 MiB")
|
||||
}
|
||||
name := safeChatAttachmentName(attachment.Name)
|
||||
mime := strings.TrimSpace(attachment.Mime)
|
||||
if mime == "" {
|
||||
mime = "application/octet-stream"
|
||||
}
|
||||
path := filepath.Join(dir, fmt.Sprintf("%d-%02d-%s", time.Now().UnixNano(), index, name))
|
||||
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("write attachment %q: %w", name, err)
|
||||
}
|
||||
if _, err := file.Write(decoded); err != nil {
|
||||
_ = file.Close()
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("write attachment %q: %w", name, err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("close attachment %q: %w", name, err)
|
||||
}
|
||||
created = append(created, path)
|
||||
uri := (&url.URL{Scheme: "file", Path: path}).String()
|
||||
files = append(files, opencode.PromptFile{URI: uri, Name: name})
|
||||
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartFile, Name: name, Mime: mime, URI: uri})
|
||||
}
|
||||
return files, parts, nil
|
||||
}
|
||||
|
||||
func safeChatAttachmentSegment(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
value = strings.Map(func(r rune) rune {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
|
||||
return r
|
||||
default:
|
||||
return '_'
|
||||
}
|
||||
}, value)
|
||||
if value == "" {
|
||||
return "session"
|
||||
}
|
||||
if len(value) > 80 {
|
||||
value = value[:80]
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func safeChatAttachmentName(value string) string {
|
||||
name := filepath.Base(strings.TrimSpace(value))
|
||||
name = strings.Map(func(r rune) rune {
|
||||
if r == 0 || r == '/' || r == '\\' {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, name)
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" || name == "." {
|
||||
name = "attachment"
|
||||
}
|
||||
if len(name) > 120 {
|
||||
ext := filepath.Ext(name)
|
||||
if len(ext) > 16 {
|
||||
ext = ""
|
||||
}
|
||||
name = name[:120-len(ext)] + ext
|
||||
}
|
||||
return name
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestPrepareChatAttachmentsWritesPrivateFileAndPart(t *testing.T) {
|
||||
data := base64.StdEncoding.EncodeToString([]byte("hello attachment"))
|
||||
files, parts, err := prepareChatAttachments("ses_test", []protocol.ChatAttachment{{
|
||||
Name: "../../note.txt", Mime: "text/plain", Data: data,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(files) != 1 || len(parts) != 1 {
|
||||
t.Fatalf("files=%d parts=%d", len(files), len(parts))
|
||||
}
|
||||
if files[0].Name != "note.txt" || parts[0].Name != "note.txt" || parts[0].Mime != "text/plain" {
|
||||
t.Fatalf("attachment = %+v / %+v", files[0], parts[0])
|
||||
}
|
||||
path := strings.TrimPrefix(files[0].URI, "file://")
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != "hello attachment" {
|
||||
t.Fatalf("body = %q", body)
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("mode = %o, want 0600", info.Mode().Perm())
|
||||
}
|
||||
if filepath.Dir(path) == filepath.Dir("/tmp") {
|
||||
t.Fatalf("attachment escaped its private directory: %s", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareChatAttachmentsRejectsInvalidAndOversized(t *testing.T) {
|
||||
if _, _, err := prepareChatAttachments("ses_test", []protocol.ChatAttachment{{Name: "x", Data: "not base64"}}); err == nil {
|
||||
t.Fatal("invalid base64 accepted")
|
||||
}
|
||||
oversized := base64.StdEncoding.EncodeToString(make([]byte, maxChatAttachmentBytes+1))
|
||||
if _, _, err := prepareChatAttachments("ses_test", []protocol.ChatAttachment{{Name: "big", Data: oversized}}); err == nil {
|
||||
t.Fatal("oversized attachment accepted")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
@@ -136,6 +137,20 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
|
||||
return adapter.Prompt(ctx, sessionID, text)
|
||||
}
|
||||
|
||||
// PromptWithMessageIDFiles forwards a prompt with the private local files the
|
||||
// server wrote for browser attachments. A backend without file support falls
|
||||
// back to the text-only path rather than dropping the prompt.
|
||||
func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, text, messageID string, files []opencode.PromptFile) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if withFiles, ok := adapter.(chatPromptWithFiles); ok {
|
||||
return withFiles.PromptWithMessageIDFiles(ctx, sessionID, text, messageID, files)
|
||||
}
|
||||
return m.PromptWithMessageID(ctx, sessionID, text, messageID)
|
||||
}
|
||||
|
||||
func (m *chatManager) Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
|
||||
@@ -101,6 +101,7 @@ func (s *chatSub) close() {
|
||||
// reported to the client that sent it.
|
||||
type chatQueuedPrompt struct {
|
||||
text string
|
||||
files []opencode.PromptFile
|
||||
operationID string
|
||||
nativeID string
|
||||
requestID string
|
||||
@@ -548,6 +549,17 @@ func (h *chatHub) submitPrompt(sessionID string, p *chatQueuedPrompt) (queued bo
|
||||
return false, false
|
||||
}
|
||||
|
||||
// turnRunning reports whether the session has a turn in flight. A client that
|
||||
// subscribes after a turn started (for example the operator's browser while the
|
||||
// CLI harness is working) needs this to show Stop and the live activity line;
|
||||
// the room's own frames only cover events after the subscription.
|
||||
func (h *chatHub) turnRunning(sessionID string) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
room := h.rooms[sessionID]
|
||||
return room != nil && room.running
|
||||
}
|
||||
|
||||
// pendingFrames returns a copy of the room's unresolved approval requests so a
|
||||
// client that attaches after they were raised can be shown every one of them. It
|
||||
// returns nil when the room holds none.
|
||||
@@ -676,7 +688,9 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{
|
||||
}
|
||||
}
|
||||
var promptErr error
|
||||
if withID, ok := broker.(chatPromptWithMessageID); ok {
|
||||
if withFiles, ok := broker.(chatPromptWithFiles); ok && len(p.files) > 0 {
|
||||
promptErr = withFiles.PromptWithMessageIDFiles(room.ctx, room.sessionID, p.text, p.nativeID, p.files)
|
||||
} else if withID, ok := broker.(chatPromptWithMessageID); ok {
|
||||
promptErr = withID.PromptWithMessageID(room.ctx, room.sessionID, p.text, p.nativeID)
|
||||
} else {
|
||||
promptErr = broker.Prompt(room.ctx, room.sessionID, p.text)
|
||||
|
||||
@@ -45,6 +45,11 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat prompt exceeds 64 KiB"})
|
||||
return
|
||||
}
|
||||
attachmentFiles, attachmentParts, err := prepareChatAttachments(prompt.SessionID, prompt.Attachments)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
sessionID := prompt.SessionID
|
||||
sub := hub.attach(sessionID, clientID, sanitizeChatClientLabel(prompt.Client), broker, write)
|
||||
if sub == nil {
|
||||
@@ -58,6 +63,7 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
|
||||
MessageID: prompt.NativeMessageID,
|
||||
Kind: protocol.ChatEventUser,
|
||||
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: prompt.Text},
|
||||
Attachments: attachmentParts,
|
||||
Client: sub.label,
|
||||
OperationID: prompt.OperationID,
|
||||
}
|
||||
@@ -66,10 +72,14 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
|
||||
}
|
||||
queued, refused := hub.submitPrompt(sessionID, &chatQueuedPrompt{
|
||||
text: prompt.Text,
|
||||
files: attachmentFiles,
|
||||
operationID: prompt.OperationID,
|
||||
nativeID: userFrame.MessageID,
|
||||
requestID: request.ID,
|
||||
write: write,
|
||||
// Only the caller's real OpenCode message id is forwarded. The hub's own
|
||||
// `usr_` display id is not a valid OpenCode `msg_` id, so a client that
|
||||
// omitted native_message_id lets OpenCode generate one instead.
|
||||
nativeID: prompt.NativeMessageID,
|
||||
requestID: request.ID,
|
||||
write: write,
|
||||
})
|
||||
if refused {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " already has the maximum number of prompts queued"})
|
||||
@@ -125,6 +135,17 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not observe session " + query.SessionID})
|
||||
return
|
||||
}
|
||||
// A turn already in flight when this client attaches has no `step started`
|
||||
// frame in its future, so replay the live marker. The composer's Stop control
|
||||
// and the transcript's one activity row read it; the later `step ended` frame
|
||||
// settles them normally.
|
||||
if hub.turnRunning(query.SessionID) {
|
||||
sub.send(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
|
||||
SessionID: query.SessionID,
|
||||
Kind: protocol.ChatEventStep,
|
||||
Step: &protocol.ChatStep{Status: protocol.ChatStepStarted},
|
||||
}})
|
||||
}
|
||||
// Replay every still-unresolved approval request the room holds, not only the
|
||||
// most recent one, so a client that attaches after two requests were raised
|
||||
// still sees both cards.
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -41,6 +42,7 @@ func newOperatorStore(t *testing.T) *pipeline.Store {
|
||||
type fakeChat struct {
|
||||
mu sync.Mutex
|
||||
promptCalls int
|
||||
promptFiles []opencode.PromptFile
|
||||
interrupts int
|
||||
replies int
|
||||
replyRequest protocol.ChatReplyRequest
|
||||
@@ -107,6 +109,13 @@ func (f *fakeChat) Prompt(context.Context, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeChat) PromptWithMessageIDFiles(ctx context.Context, sessionID, text, _ string, files []opencode.PromptFile) error {
|
||||
f.mu.Lock()
|
||||
f.promptFiles = append([]opencode.PromptFile(nil), files...)
|
||||
f.mu.Unlock()
|
||||
return f.Prompt(ctx, sessionID, text)
|
||||
}
|
||||
|
||||
func (f *fakeChat) Stream(ctx context.Context, _ string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
f.mu.Lock()
|
||||
f.subscribed = true
|
||||
@@ -409,6 +418,43 @@ func readChatTurn(t *testing.T, ctx context.Context, conn *websocket.Conn) []pro
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatPromptWritesAttachmentAndForwardsLocalFile(t *testing.T) {
|
||||
broker := scriptedChat()
|
||||
ctx, _, conn := dialChat(t, broker)
|
||||
data := base64.StdEncoding.EncodeToString([]byte("hello attachment"))
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{
|
||||
SessionID: "ses_1",
|
||||
Text: "read the attached note",
|
||||
Attachments: []protocol.ChatAttachment{{
|
||||
Name: "note.txt", Mime: "text/plain", Data: data,
|
||||
}},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ack protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ack.Type != protocol.ChatPrompt || ack.Error != "" {
|
||||
t.Fatalf("ack = %+v", ack)
|
||||
}
|
||||
_ = readChatTurn(t, ctx, conn)
|
||||
broker.mu.Lock()
|
||||
files := append([]opencode.PromptFile(nil), broker.promptFiles...)
|
||||
broker.mu.Unlock()
|
||||
if len(files) != 1 || files[0].Name != "note.txt" {
|
||||
t.Fatalf("prompt files = %+v", files)
|
||||
}
|
||||
path := strings.TrimPrefix(files[0].URI, "file://")
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != "hello attachment" {
|
||||
t.Fatalf("attachment body = %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatPromptStreamsEvents(t *testing.T) {
|
||||
broker := scriptedChat()
|
||||
ctx, _, conn := dialChat(t, broker)
|
||||
|
||||
+20
-11
@@ -674,18 +674,17 @@ func (r *runner) cancel(id int64) error {
|
||||
r.mu.Lock()
|
||||
entry, ok := r.active[id]
|
||||
r.mu.Unlock()
|
||||
if ok {
|
||||
entry.cancel()
|
||||
return nil
|
||||
}
|
||||
// A run that is waiting on a person has no live goroutine, so cancel it at
|
||||
// the persistence layer instead. This keeps cancel working across a restart.
|
||||
// The single follow-up read seeds the terminal delta; cancel is a cold
|
||||
// operator action, not a per-transition hot path.
|
||||
if err := r.store.CancelWaiting(r.ctx, id); err != nil {
|
||||
// Persist the cancellation before asking the runner to stop. A stage that is
|
||||
// stuck in a context-unaware provider call must not leave the run "running":
|
||||
// the operator's Stop is a terminal decision, and the live row/step show it
|
||||
// immediately. FinishStep/FinishRun only update active rows, so the late
|
||||
// stage return cannot undo this.
|
||||
if err := r.store.Cancel(r.ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
// A canceled run is terminal: nothing more can notify for it.
|
||||
if ok {
|
||||
entry.cancel()
|
||||
}
|
||||
r.forgetAttention(id)
|
||||
if r.events != nil {
|
||||
if detail, err := r.store.GetRun(r.ctx, id); err == nil && detail != nil {
|
||||
@@ -1265,7 +1264,17 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
// Cancel wins over a late stage result: the store already marked the run
|
||||
// canceled and FinishRun only updates queued/running rows. Read the
|
||||
// actual state so this turn emits and notifies canceled, never a failure
|
||||
// caused by the canceled step's persistence guard.
|
||||
if detail, getErr := r.store.GetRun(c, id); getErr == nil && detail != nil && detail.Status == protocol.RunStatusCanceled {
|
||||
status = protocol.RunStatusCanceled
|
||||
outcome = detail.Outcome
|
||||
diagnostic = detail.Diagnostic
|
||||
} else {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
}
|
||||
// Push the terminal delta before the attention notification, so a slow ntfy
|
||||
// never delays the live update the app folds.
|
||||
|
||||
Reference in New Issue
Block a user