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:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user