diff --git a/internal/opencode/chat.go b/internal/opencode/chat.go index 63f3ade2..2640c394 100644 --- a/internal/opencode/chat.go +++ b/internal/opencode/chat.go @@ -85,10 +85,25 @@ func (c *Chat) Prompt(ctx context.Context, id, text string) error { return c.PromptWithMessageID(ctx, id, text, "") } +// PromptFile is one local file handed to OpenCode with a prompt. URI is the +// file:// URL the server wrote; Name is the browser's display name. +type PromptFile struct { + URI string + Name string +} + // PromptWithMessageID forwards the caller's canonical message id to OpenCode. // OpenCode persists this id in history, which is the only safe bridge between // the live user echo and an authoritative history page. func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error { + return c.PromptWithMessageIDFiles(ctx, id, text, messageID, nil) +} + +// PromptWithMessageIDFiles is PromptWithMessageID with local file attachments. +// The V2 prompt body accepts a `files` array of {uri,name}; the server writes +// browser bytes to a private temporary file first, because a browser's own file +// reference is not readable by an OpenCode service on another machine. +func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID string, files []PromptFile) error { if !sessionID.MatchString(id) { return fmt.Errorf("invalid OpenCode session id") } @@ -102,7 +117,29 @@ func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID stri if messageID != "" { body["id"] = messageID } - if _, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil { + if len(files) > 0 { + attachments := make([]map[string]string, 0, len(files)) + for _, file := range files { + if strings.TrimSpace(file.URI) == "" { + continue + } + item := map[string]string{"uri": file.URI} + if name := strings.TrimSpace(file.Name); name != "" { + item["name"] = name + } + attachments = append(attachments, item) + } + if len(attachments) > 0 { + body["files"] = attachments + } + } + if evidence, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil { + if reason := strings.TrimSpace(string(evidence)); reason != "" { + if len(reason) > 300 { + reason = reason[:300] + } + return fmt.Errorf("%w: %s", err, reason) + } return err } return nil @@ -1158,6 +1195,20 @@ type nativeChatMessage struct { CreatedAt int64 `json:"created"` } `json:"info"` Parts []nativeChatPart `json:"parts"` + // Files are the V2 user turn's attached files. They live on the message + // envelope (not in Parts), with an inline data field the history mapper must + // not expose. + Files []nativeChatFile `json:"files"` +} + +type nativeChatFile struct { + Data string `json:"data"` + Mime string `json:"mime"` + Name string `json:"name"` + Source struct { + Type string `json:"type"` + URI string `json:"uri"` + } `json:"source"` } // nativeChatModel is the nested Model.Ref a V2 turn carries ({id, providerID, @@ -1175,6 +1226,8 @@ type nativeChatPart struct { ID string `json:"id"` Text string `json:"text"` Name string `json:"name"` + URI string `json:"uri"` + Mime string `json:"mime"` Executed bool `json:"executed"` State *protocol.ChatToolState `json:"state"` Time *protocol.ChatTime `json:"time"` @@ -1280,6 +1333,11 @@ func mapChatMessages(sessionID string, records []nativeChatMessage) []protocol.C out.Parts = append(out.Parts, protocol.ChatPart{Type: part.Type, ID: part.ID, Text: part.Text}) case protocol.ChatPartTool: out.Parts = append(out.Parts, protocol.ChatPart{Type: protocol.ChatPartTool, ID: part.ID, Name: part.Name, Executed: part.Executed, State: part.State, Time: part.Time}) + case protocol.ChatPartFile: + if part.URI == "" && part.Name == "" { + continue + } + out.Parts = append(out.Parts, protocol.ChatPart{Type: protocol.ChatPartFile, Name: part.Name, URI: part.URI, Mime: part.Mime}) } } // A V2 user turn carries its prompt text as a message-level string rather @@ -1287,6 +1345,21 @@ func mapChatMessages(sessionID string, records []nativeChatMessage) []protocol.C if len(out.Parts) == 0 && role == protocol.ChatRoleUser && record.Text != "" { out.Parts = append(out.Parts, protocol.ChatPart{Type: protocol.ChatPartText, Text: record.Text}) } + // Attached files are top-level on the user envelope. Keep their name, + // MIME and file URI for the transcript; never copy the base64 data into + // history. + for _, file := range record.Files { + uri := file.Source.URI + if uri == "" { + continue + } + out.Parts = append(out.Parts, protocol.ChatPart{ + Type: protocol.ChatPartFile, + Name: file.Name, + URI: uri, + Mime: file.Mime, + }) + } messages = append(messages, out) } return messages diff --git a/internal/opencode/chat_test.go b/internal/opencode/chat_test.go index 09ab0284..7bb7f261 100644 --- a/internal/opencode/chat_test.go +++ b/internal/opencode/chat_test.go @@ -501,6 +501,44 @@ func TestDecodeChatMessagesSkipsUnknownPartsAndRoles(t *testing.T) { } } +func TestDecodeChatMessagesMapsTopLevelUserFiles(t *testing.T) { + raw := `{"data":[{"id":"msg_user","time":{"created":1},"type":"user","text":"see attached","files":[ + {"data":"aGVsbG8=","mime":"text/plain","source":{"type":"uri","uri":"file:///tmp/note.txt"},"name":"note.txt"} + ]}]}` + messages, err := decodeChatMessages("ses_1", []byte(raw)) + if err != nil { + t.Fatal(err) + } + if len(messages) != 1 || len(messages[0].Parts) != 2 { + t.Fatalf("messages = %+v", messages) + } + file := messages[0].Parts[1] + if file.Type != protocol.ChatPartFile || file.Name != "note.txt" || file.URI != "file:///tmp/note.txt" || file.Mime != "text/plain" { + t.Fatalf("file part = %+v", file) + } + if strings.Contains(file.URI, "aGVsbG8=") { + t.Fatal("history exposed inline file data") + } +} + +func TestDecodeChatMessagesMapsUserFileParts(t *testing.T) { + raw := `{"data":[{"id":"msg_user","time":{"created":1},"type":"user","parts":[ + {"type":"text","text":"see attached"}, + {"type":"file","uri":"file:///tmp/note.txt","name":"note.txt","mime":"text/plain"} + ]}]}` + messages, err := decodeChatMessages("ses_1", []byte(raw)) + if err != nil { + t.Fatal(err) + } + if len(messages) != 1 || len(messages[0].Parts) != 2 { + t.Fatalf("messages = %+v", messages) + } + file := messages[0].Parts[1] + if file.Type != protocol.ChatPartFile || file.Name != "note.txt" || file.URI != "file:///tmp/note.txt" || file.Mime != "text/plain" { + t.Fatalf("file part = %+v", file) + } +} + func TestChatMessagesPagesLargeToolHistoryWithoutGlobalResponseLimit(t *testing.T) { large := strings.Repeat("x", MaxResponse+1) var paths []string diff --git a/internal/opencode/chat_v2_test.go b/internal/opencode/chat_v2_test.go index 805d3892..37c16425 100644 --- a/internal/opencode/chat_v2_test.go +++ b/internal/opencode/chat_v2_test.go @@ -83,6 +83,34 @@ func TestChatV2PromptWithMessageID(t *testing.T) { } } +func TestChatV2PromptWithFiles(t *testing.T) { + var body struct { + Text string `json:"text"` + Files []map[string]string `json:"files"` + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatal(err) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":{"id":"msg_files","sessionID":"ses_1","type":"user"}}`)) + })) + defer srv.Close() + chat := NewChat(&Connection{Backend: "v2", URL: srv.URL}) + err := chat.PromptWithMessageIDFiles(context.Background(), "ses_1", "read this", "msg_files", []PromptFile{ + {URI: "file:///tmp/note.txt", Name: "note.txt"}, + }) + if err != nil { + t.Fatal(err) + } + if body.Text != "read this" || len(body.Files) != 1 { + t.Fatalf("prompt body = %+v", body) + } + if body.Files[0]["uri"] != "file:///tmp/note.txt" || body.Files[0]["name"] != "note.txt" { + t.Fatalf("file = %+v", body.Files[0]) + } +} + // TestChatStreamRealV2Shapes replays the exact event frames the installed 2.0.20 // service emitted on /api/event during a live turn (captured, not documented): // a step start, token text delta, usage and a step end whose data carries no diff --git a/internal/pipeline/human_test.go b/internal/pipeline/human_test.go index 7ee91f9c..24672851 100644 --- a/internal/pipeline/human_test.go +++ b/internal/pipeline/human_test.go @@ -183,6 +183,43 @@ func TestResolveDecisionValidUnknownRepeatAndNotWaiting(t *testing.T) { } } +func TestCancelRunningRunMarksRunAndLiveStep(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "cancel-running.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if _, err := store.Submit(ctx, "humangate", humanSource); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + definition, err := store.Get(ctx, items[0].ID, 1) + if err != nil { + t.Fatal(err) + } + id, _, err := store.CreateRun(ctx, definition, "run", "workspace", false, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + if err := store.BeginStep(ctx, id, 1, "gate", map[string]any{"prompt": "task"}); err != nil { + t.Fatal(err) + } + if err := store.Cancel(ctx, id); err != nil { + t.Fatal(err) + } + detail, err := store.GetRun(ctx, id) + if err != nil { + t.Fatal(err) + } + if detail.Status != "canceled" || detail.Steps[0].Status != "canceled" { + t.Fatalf("running run not canceled immediately: %+v %+v", detail.RunSummary, detail.Steps) + } + if err := store.Cancel(ctx, id); err == nil { + t.Fatal("canceling an already-canceled run succeeded") + } +} + func TestCancelWaitingRun(t *testing.T) { ctx := context.Background() store, err := Open(filepath.Join(t.TempDir(), "cancel.db")) diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index d27e7268..8a0536f2 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -305,6 +305,37 @@ func (s *Store) CancelWaiting(ctx context.Context, id int64) error { return tx.Commit() } +// Cancel immediately marks an active run and its live step canceled. The +// runner's context is canceled too, but a harness that ignores cancellation (or +// is stuck awaiting a provider) must not leave the operator looking at a run +// that still says "running" after they pressed Stop. +func (s *Store) Cancel(ctx context.Context, id int64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs +SET status='canceled', diagnostic=CASE WHEN diagnostic='' THEN 'Canceled by operator' ELSE diagnostic END, finished_at=CURRENT_TIMESTAMP +WHERE id=? AND status IN ('queued','running','waiting')`, id) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n != 1 { + return fmt.Errorf("run is not active or waiting") + } + if _, err := tx.ExecContext(ctx, `UPDATE run_steps +SET status='canceled', diagnostic=CASE WHEN diagnostic='' THEN 'Canceled by operator' ELSE diagnostic END, finished_at=CURRENT_TIMESTAMP +WHERE run_id=? AND status IN ('running','waiting')`, id); err != nil { + return err + } + return tx.Commit() +} + func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagnostic string, output map[string]any) error { data, err := json.Marshal(output) if err != nil { diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 0a6e90ca..08f4b982 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -88,6 +88,7 @@ const ( ChatPartText = "text" ChatPartReasoning = "reasoning" ChatPartTool = "tool" + ChatPartFile = "file" ) // ChatEvent.Kind values pushed on the chat_event stream. Step and usage carry @@ -273,6 +274,21 @@ type ChatPromptRequest struct { // sent with the prompt so history can be reconciled without guessing from // text, time, order or page boundaries. NativeMessageID string `json:"native_message_id,omitempty"` + // Attachments carries the bytes of files picked or pasted in the browser. + // Files are local to the browser, so a reference string alone is not enough + // for a server on another machine; Data is standard base64 and the server + // writes it to a private temporary file before prompting the agent. + Attachments []ChatAttachment `json:"attachments,omitempty"` +} + +// ChatAttachment is one browser attachment carried by a chat prompt. Data is +// standard base64 (no data: prefix); Name is a display name and Mime is the +// browser's content type. The server derives the on-disk name and never trusts +// either for path construction. +type ChatAttachment struct { + Name string `json:"name"` + Mime string `json:"mime,omitempty"` + Data string `json:"data"` } // ChatMessage is one stored turn returned by chat_messages. A user turn is a @@ -313,6 +329,8 @@ type ChatPart struct { ID string `json:"id,omitempty"` Text string `json:"text,omitempty"` Name string `json:"name,omitempty"` + URI string `json:"uri,omitempty"` + Mime string `json:"mime,omitempty"` Executed bool `json:"executed,omitempty"` State *ChatToolState `json:"state,omitempty"` Time *ChatTime `json:"time,omitempty"` @@ -365,13 +383,16 @@ type ChatTime struct { // tool carries a full Part with its state, step marks turn progress and usage // reports the turn's totals. type ChatEventFrame struct { - SessionID string `json:"session_id"` - MessageID string `json:"message_id,omitempty"` - Kind string `json:"kind"` - Delta string `json:"delta,omitempty"` - Part *ChatPart `json:"part,omitempty"` - Step *ChatStep `json:"step,omitempty"` - Usage *ChatUsage `json:"usage,omitempty"` + SessionID string `json:"session_id"` + MessageID string `json:"message_id,omitempty"` + Kind string `json:"kind"` + Delta string `json:"delta,omitempty"` + Part *ChatPart `json:"part,omitempty"` + // Attachments carries the file parts of a user turn another client sent. + // A frame has one Part, so the prompt's files travel alongside its text. + Attachments []ChatPart `json:"attachments,omitempty"` + Step *ChatStep `json:"step,omitempty"` + Usage *ChatUsage `json:"usage,omitempty"` // Shell is the payload of a ChatEventShell frame: the shell's id, its // status, the command it is running and (once it has exited) its exit code. // It is nil on every other kind. diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index 19e4d089..a80487c0 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -24,6 +24,7 @@ const ( RunStatusQueued = "queued" RunStatusWaiting = "waiting" RunStatusRunning = "running" + RunStatusCanceled = "canceled" StepStatusRunning = "running" StepStatusWaiting = "waiting" // NotifyWaiting is the notification event a human stage emits when it parks diff --git a/internal/server/chat.go b/internal/server/chat.go index bb697bee..dbfd7525 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -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. diff --git a/internal/server/chat_attachments.go b/internal/server/chat_attachments.go new file mode 100644 index 00000000..5ecb2641 --- /dev/null +++ b/internal/server/chat_attachments.go @@ -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 +} diff --git a/internal/server/chat_attachments_test.go b/internal/server/chat_attachments_test.go new file mode 100644 index 00000000..9fec91ed --- /dev/null +++ b/internal/server/chat_attachments_test.go @@ -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") + } +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index adc97f09..17ada756 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -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 { diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index e21d1366..784c6a74 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -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) diff --git a/internal/server/chat_stream.go b/internal/server/chat_stream.go index 7ca66265..f173abc0 100644 --- a/internal/server/chat_stream.go +++ b/internal/server/chat_stream.go @@ -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. diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index c4c567c7..db32da4a 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -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) diff --git a/internal/server/runner.go b/internal/server/runner.go index f56a1813..c2b0430d 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -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. diff --git a/web/src/repository.js b/web/src/repository.js index a3b643cd..daf69f7f 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -433,13 +433,12 @@ export class PipelinesRepository { * prompt behind an in-flight turn (`chat_queued` on the reply), which is the * one signal the composer's queued notice is derived from. * - * Note: the server's prompt path (`internal/server/chat_stream.go`) consumes - * only `text` today — `files` is accepted on the wire but not yet forwarded to - * OpenCode, so a browser attachment is collected, validated and made to block a - * failed send, then sent best-effort as the file's own reference string. The - * attachment is not yet delivered to the agent; the row note records that. + * Browser attachments travel in `attachments` as {name,mime,data} with data + * encoded as standard base64. The server writes them to private temporary + * files and hands those file:// references to OpenCode; `files` remains the + * legacy reference-only field for older clients. */ - async chatPrompt(sessionId, text, files = [], operationId = newChatOperationId()) { + async chatPrompt(sessionId, text, files = [], operationId = newChatOperationId(), attachments = []) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } @@ -454,6 +453,7 @@ export class PipelinesRepository { native_message_id: nativeChatMessageId(operationId), }; if (files.length > 0) body.files = files; + if (attachments.length > 0) body.attachments = attachments; const response = await this.#client.call({ type: Protocol.CHAT_PROMPT, [ChatKeys.PROMPT]: body }); return Boolean(response[ChatKeys.QUEUED]); } diff --git a/web/test/repository.test.mjs b/web/test/repository.test.mjs index 6952ccb1..f376418a 100644 --- a/web/test/repository.test.mjs +++ b/web/test/repository.test.mjs @@ -367,6 +367,17 @@ test("chatPrompt includes files when present and reads chat_queued", async () => assert.equal(queued, true); }); +test("chatPrompt sends browser attachment bytes with their name and mime", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt" }); + await repo.chatPrompt("s1", "see attached", [], "op-3", [ + { name: "note.txt", mime: "text/plain", data: "aGVsbG8=" }, + ]); + assert.deepEqual(lastFrame(ws).chat_prompt.attachments, [ + { name: "note.txt", mime: "text/plain", data: "aGVsbG8=" }, + ]); +}); + test("chatPrompt refuses a blank session or blank text without sending", async () => { const { repo, ws } = connected(); await assert.rejects(() => repo.chatPrompt(" ", "hi", [], "op"), ProtocolError);