## What
Adds `POST /api/v2/chats/{chat}/workspace-files`, which streams the
request body to the chat's bound workspace agent and returns the final
path/name/size, plus the `workspace-file-reference` message part type
that carries the uploaded file's metadata through chat messages:
- `coderd/exp_chats.go`: owner-only middleware (chat RBAC update +
reject archived), workspace exec authorization (403/409 like the
existing chat exec paths), agent selection (prefer the chat's bound
agent, else deterministic `agentselect.FindChatAgent`, without
persisting a binding), 30s dial timeout, chat/ancestor tracking headers
on the agent connection, and agent error passthrough (agent HTTP status
preserved, 502 with a generic detail for transport failures; the real
error is logged). Deleted and non-running workspaces get a specific 409
("Workspace is stopped. Start the workspace before uploading files.")
before agent lookup. Each failed upload logs one structured warning, and
`coderd_chat_workspace_upload_total{status}` counts outcomes. The route
shares the files rate limit and documents its 429.
- Input validation: client-supplied `workspace-file-reference` parts
must point inside `/.coder/chats/<chat-id>/files/` with a matching
basename, non-negative size, and a `workspace_file_workspace_id` equal
to the chat's currently bound workspace (the upload response echoes it
as `workspace_id`). References uploaded before a workspace rebind are
rejected instead of silently sending the agent an unreadable path. The
file name must already be in sanitized form
(`SanitizeWorkspaceUploadName(name) == name`), and the cleaned path and
base media type are what gets persisted; message edits share the same
validation. Parts are rejected on chat creation (no chat ID exists yet).
- `coderd/x/chatd/chatprompt`: references render into the prompt as text
only, `[workspace file: <name> (<size>) at <path>]`; file bytes never
reach the LLM. Title derivation (`TitleText`) uses the bare file name,
so fallback titles carry no internal marker.
- `codersdk`: part-type constants/fields,
`ChatMessageWorkspaceFileReference` builder, and
`Client.UploadChatWorkspaceFile` (RFC 5987 filename in
`Content-Disposition`).
No DB migration: parts persist as JSON in `chat_messages.content`.
## Why
Bridges chat and the workspace filesystem for CODAGT-211: users drop a
file in chat, the bytes land where the agent's tools can operate on
them, and the model learns the path from the reference part.
## How tested
- `go test ./coderd -run 'WorkspaceFile|ChatInput|UploadChat'` including
an integration test that runs a real in-memory agent, uploads through
the coderd route, verifies bytes on disk, and exercises collision
suffixes.
- `go test ./codersdk ./coderd/x/chatd/...`, `make gen`
(swagger/types/docs), `make lint`.
- Rebased onto main 2026-09-21: the chat API moved from
`/api/experimental` to `/api/v2`, so the route is registered in
`coderd/chat_routes.go` and the SDK method lives on `codersdk.Client`.
## Follow-ups
- The files rate limit counts requests, not bytes or concurrency;
whether this route should use a per-user concurrency cap instead, and
whether the new-chat page should keep partial successes on a 429, is
still open
([CODAGT-1171](https://linear.app/codercom/issue/CODAGT-1171)).
Part of CODAGT-211. Stack: agent API -> coderd endpoint (this PR) -> UI.
> This PR was authored by Mux (AI) working on Mike's behalf.
205 lines
5.7 KiB
Go
205 lines
5.7 KiB
Go
package chatprompt_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"strings"
|
|
"testing"
|
|
|
|
"charm.land/fantasy"
|
|
"github.com/google/uuid"
|
|
"github.com/sqlc-dev/pqtype"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"cdr.dev/slog/v3/sloggers/slogtest"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
)
|
|
|
|
// userFileMessage builds a single persisted user message holding one
|
|
// file_id-backed file part, plus a resolver that returns the given
|
|
// bytes, media type, and filename for that file.
|
|
func userFileMessage(t *testing.T, name, mediaType string, data []byte) ([]database.ChatMessage, chatprompt.FileResolver) {
|
|
t.Helper()
|
|
fileID := uuid.New()
|
|
rawContent := mustJSON(t, []json.RawMessage{
|
|
mustJSON(t, map[string]any{
|
|
"type": "file",
|
|
"data": map[string]any{
|
|
"media_type": mediaType,
|
|
"file_id": fileID.String(),
|
|
},
|
|
}),
|
|
})
|
|
messages := []database.ChatMessage{{
|
|
Role: database.ChatMessageRoleUser,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
Content: pqtype.NullRawMessage{RawMessage: rawContent, Valid: true},
|
|
}}
|
|
resolver := func(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]chatprompt.FileData, error) {
|
|
result := make(map[uuid.UUID]chatprompt.FileData)
|
|
for _, id := range ids {
|
|
if id == fileID {
|
|
result[id] = chatprompt.FileData{
|
|
Name: name,
|
|
Data: data,
|
|
MediaType: mediaType,
|
|
}
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
return messages, resolver
|
|
}
|
|
|
|
func acceptAll(string) bool { return true }
|
|
func acceptNone(string) bool { return false }
|
|
|
|
func TestConvertMessagesWithFiles_InlinesTextFilePartWhenProviderRejects(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
cases := []struct {
|
|
name string
|
|
fileName string
|
|
mediaType string
|
|
data []byte
|
|
accepts func(string) bool
|
|
wantText bool // true = TextPart, false = FilePart
|
|
}{
|
|
{
|
|
name: "json rejected becomes text",
|
|
fileName: "data.json",
|
|
mediaType: "application/json",
|
|
data: []byte(`{"hello":"world"}`),
|
|
accepts: acceptNone,
|
|
wantText: true,
|
|
},
|
|
{
|
|
name: "text accepted stays file",
|
|
fileName: "notes.txt",
|
|
mediaType: "text/plain",
|
|
data: []byte("plain text body"),
|
|
accepts: acceptAll,
|
|
wantText: false,
|
|
},
|
|
{
|
|
name: "text rejected becomes text",
|
|
fileName: "notes.txt",
|
|
mediaType: "text/plain",
|
|
data: []byte("plain text body"),
|
|
accepts: acceptNone,
|
|
wantText: true,
|
|
},
|
|
{
|
|
name: "markdown rejected becomes text",
|
|
fileName: "README.md",
|
|
mediaType: "text/markdown",
|
|
data: []byte("# Title"),
|
|
accepts: acceptNone,
|
|
wantText: true,
|
|
},
|
|
{
|
|
name: "svg rejected becomes text despite image prefix",
|
|
fileName: "diagram.svg",
|
|
mediaType: "image/svg+xml",
|
|
data: []byte(`<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`),
|
|
accepts: acceptNone,
|
|
wantText: true,
|
|
},
|
|
{
|
|
name: "image never decoded even when rejected",
|
|
fileName: "pic.png",
|
|
mediaType: "image/png",
|
|
data: []byte("not really png"),
|
|
accepts: acceptNone,
|
|
wantText: false,
|
|
},
|
|
{
|
|
name: "octet-stream never decoded even when rejected",
|
|
fileName: "blob.bin",
|
|
mediaType: "application/octet-stream",
|
|
data: []byte("binary"),
|
|
accepts: acceptNone,
|
|
wantText: false,
|
|
},
|
|
}
|
|
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
messages, resolver := userFileMessage(t, tc.fileName, tc.mediaType, tc.data)
|
|
prompt, err := chatprompt.ConvertMessagesWithFiles(
|
|
context.Background(),
|
|
messages,
|
|
resolver,
|
|
slogtest.Make(t, nil),
|
|
tc.accepts,
|
|
uuid.NullUUID{},
|
|
)
|
|
require.NoError(t, err)
|
|
require.Len(t, prompt, 1)
|
|
require.Len(t, prompt[0].Content, 1)
|
|
|
|
if tc.wantText {
|
|
textPart, ok := fantasy.AsMessagePart[fantasy.TextPart](prompt[0].Content[0])
|
|
require.True(t, ok, "expected TextPart")
|
|
require.Contains(t, textPart.Text, tc.fileName)
|
|
require.Contains(t, textPart.Text, string(tc.data))
|
|
return
|
|
}
|
|
|
|
filePart, ok := fantasy.AsMessagePart[fantasy.FilePart](prompt[0].Content[0])
|
|
require.True(t, ok, "expected FilePart")
|
|
require.Equal(t, tc.data, filePart.Data)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestConvertMessagesWithFiles_NilPredicateKeepsFilePart(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
data := []byte(`{"a":1}`)
|
|
messages, resolver := userFileMessage(t, "data.json", "application/json", data)
|
|
prompt, err := chatprompt.ConvertMessagesWithFiles(
|
|
context.Background(),
|
|
messages,
|
|
resolver,
|
|
slogtest.Make(t, nil),
|
|
nil,
|
|
uuid.NullUUID{},
|
|
)
|
|
require.NoError(t, err)
|
|
require.Len(t, prompt, 1)
|
|
require.Len(t, prompt[0].Content, 1)
|
|
filePart, ok := fantasy.AsMessagePart[fantasy.FilePart](prompt[0].Content[0])
|
|
require.True(t, ok, "expected FilePart when predicate is nil")
|
|
require.Equal(t, data, filePart.Data)
|
|
}
|
|
|
|
func TestConvertMessagesWithFiles_InlinedTextNotTruncated(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
// A large text file is inlined in full, with no silent truncation,
|
|
// matching how a provider that accepts the media type natively would
|
|
// receive the whole file.
|
|
const budget = 128 * 1024
|
|
data := []byte(strings.Repeat("a", budget+1024))
|
|
messages, resolver := userFileMessage(t, "big.txt", "text/plain", data)
|
|
prompt, err := chatprompt.ConvertMessagesWithFiles(
|
|
context.Background(),
|
|
messages,
|
|
resolver,
|
|
slogtest.Make(t, nil),
|
|
acceptNone,
|
|
uuid.NullUUID{},
|
|
)
|
|
require.NoError(t, err)
|
|
require.Len(t, prompt, 1)
|
|
require.Len(t, prompt[0].Content, 1)
|
|
textPart, ok := fantasy.AsMessagePart[fantasy.TextPart](prompt[0].Content[0])
|
|
require.True(t, ok, "expected TextPart")
|
|
require.Contains(t, textPart.Text, string(data),
|
|
"the full file content should be inlined without truncation")
|
|
require.NotContains(t, textPart.Text, "truncated")
|
|
}
|