feat: add chat workspace file upload endpoint (#27079)
## 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.
This commit is contained in:
1 parent
47345bfc4e
commit
5dde49dffb
39 files changed
+2932
-105
No files matched your search
Generated
+165
-2
@@ -3444,6 +3444,100 @@ const docTemplate = `{
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v2/chats/{chat}/workspace-files": {
|
||||
"post": {
|
||||
"description": "Streams the request body into the chat workspace's\nupload directory. The request Content-Type header is\nrecorded as the file's media type. There is no\nserver-imposed size cap; client cancellation aborts the\nstream and the agent leaves no partial target file behind.",
|
||||
"consumes": [
|
||||
"*/*"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Chats"
|
||||
],
|
||||
"summary": "Upload a file to a chat's workspace",
|
||||
"operationId": "upload-a-file-to-a-chats-workspace",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"description": "Chat ID",
|
||||
"name": "chat",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filename of the file (attachment; filename=...)",
|
||||
"name": "Content-Disposition",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Raw file binary data",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.UploadChatWorkspaceFileResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Too Many Requests",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"502": {
|
||||
"description": "Bad Gateway",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"CoderSessionToken": []
|
||||
}
|
||||
],
|
||||
"x-apidocgen": {
|
||||
"rawBodyFile": "archive.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/connectionlog": {
|
||||
"get": {
|
||||
"produces": [
|
||||
@@ -20360,6 +20454,24 @@ const docTemplate = `{
|
||||
},
|
||||
"type": {
|
||||
"$ref": "#/definitions/codersdk.ChatInputPartType"
|
||||
},
|
||||
"workspace_file_media_type": {
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_path": {
|
||||
"description": "The following fields are only set when Type is\nChatInputPartTypeWorkspaceFileReference.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_size": {
|
||||
"type": "integer"
|
||||
},
|
||||
"workspace_file_workspace_id": {
|
||||
"description": "WorkspaceFileWorkspaceID is the workspace the file was uploaded\nto, as returned by the upload endpoint. It must match the chat's\ncurrently bound workspace.",
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -20368,12 +20480,14 @@ const docTemplate = `{
|
||||
"enum": [
|
||||
"text",
|
||||
"file",
|
||||
"file-reference"
|
||||
"file-reference",
|
||||
"workspace-file-reference"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"ChatInputPartTypeText",
|
||||
"ChatInputPartTypeFile",
|
||||
"ChatInputPartTypeFileReference"
|
||||
"ChatInputPartTypeFileReference",
|
||||
"ChatInputPartTypeWorkspaceFileReference"
|
||||
]
|
||||
},
|
||||
"codersdk.ChatMessage": {
|
||||
@@ -20578,6 +20692,27 @@ const docTemplate = `{
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_media_type": {
|
||||
"description": "WorkspaceFileMediaType is the best-effort declared MIME type.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_name": {
|
||||
"description": "WorkspaceFileName is the sanitized basename of a workspace upload.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_path": {
|
||||
"description": "WorkspaceFilePath is the absolute path of a workspace upload.\nThe bytes live on the workspace filesystem; only metadata is\npersisted on the message.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_size": {
|
||||
"description": "WorkspaceFileSize is the byte size of a workspace upload.",
|
||||
"type": "integer"
|
||||
},
|
||||
"workspace_file_workspace_id": {
|
||||
"description": "WorkspaceFileWorkspaceID identifies the workspace whose\nfilesystem holds the uploaded bytes. References are only\nreadable while the chat stays bound to that workspace.",
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -20593,6 +20728,7 @@ const docTemplate = `{
|
||||
"file-reference",
|
||||
"context-file",
|
||||
"skill",
|
||||
"workspace-file-reference",
|
||||
"hook-context",
|
||||
"hook-notice"
|
||||
],
|
||||
@@ -20606,6 +20742,7 @@ const docTemplate = `{
|
||||
"ChatMessagePartTypeFileReference",
|
||||
"ChatMessagePartTypeContextFile",
|
||||
"ChatMessagePartTypeSkill",
|
||||
"ChatMessagePartTypeWorkspaceFileReference",
|
||||
"ChatMessagePartTypeHookContext",
|
||||
"ChatMessagePartTypeHookNotice"
|
||||
]
|
||||
@@ -30620,6 +30757,32 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"codersdk.UploadChatWorkspaceFileResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"media_type": {
|
||||
"description": "MediaType is the client-declared content type for display.",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name is the final basename of the uploaded file.",
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"description": "Path is the absolute path of the file on the workspace.",
|
||||
"type": "string"
|
||||
},
|
||||
"size": {
|
||||
"description": "Size is the number of bytes written to the workspace.",
|
||||
"type": "integer"
|
||||
},
|
||||
"workspace_id": {
|
||||
"description": "WorkspaceID is the workspace whose filesystem received the\nbytes. Message parts referencing this upload must carry it.",
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
},
|
||||
"codersdk.UploadResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
Generated
+158
-2
@@ -3049,6 +3049,94 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v2/chats/{chat}/workspace-files": {
|
||||
"post": {
|
||||
"description": "Streams the request body into the chat workspace's\nupload directory. The request Content-Type header is\nrecorded as the file's media type. There is no\nserver-imposed size cap; client cancellation aborts the\nstream and the agent leaves no partial target file behind.",
|
||||
"consumes": ["*/*"],
|
||||
"produces": ["application/json"],
|
||||
"tags": ["Chats"],
|
||||
"summary": "Upload a file to a chat's workspace",
|
||||
"operationId": "upload-a-file-to-a-chats-workspace",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"description": "Chat ID",
|
||||
"name": "chat",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filename of the file (attachment; filename=...)",
|
||||
"name": "Content-Disposition",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Raw file binary data",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.UploadChatWorkspaceFileResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Too Many Requests",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
},
|
||||
"502": {
|
||||
"description": "Bad Gateway",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/codersdk.Response"
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"CoderSessionToken": []
|
||||
}
|
||||
],
|
||||
"x-apidocgen": {
|
||||
"rawBodyFile": "archive.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/connectionlog": {
|
||||
"get": {
|
||||
"produces": ["application/json"],
|
||||
@@ -18353,16 +18441,35 @@
|
||||
},
|
||||
"type": {
|
||||
"$ref": "#/definitions/codersdk.ChatInputPartType"
|
||||
},
|
||||
"workspace_file_media_type": {
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_path": {
|
||||
"description": "The following fields are only set when Type is\nChatInputPartTypeWorkspaceFileReference.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_size": {
|
||||
"type": "integer"
|
||||
},
|
||||
"workspace_file_workspace_id": {
|
||||
"description": "WorkspaceFileWorkspaceID is the workspace the file was uploaded\nto, as returned by the upload endpoint. It must match the chat's\ncurrently bound workspace.",
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
},
|
||||
"codersdk.ChatInputPartType": {
|
||||
"type": "string",
|
||||
"enum": ["text", "file", "file-reference"],
|
||||
"enum": ["text", "file", "file-reference", "workspace-file-reference"],
|
||||
"x-enum-varnames": [
|
||||
"ChatInputPartTypeText",
|
||||
"ChatInputPartTypeFile",
|
||||
"ChatInputPartTypeFileReference"
|
||||
"ChatInputPartTypeFileReference",
|
||||
"ChatInputPartTypeWorkspaceFileReference"
|
||||
]
|
||||
},
|
||||
"codersdk.ChatMessage": {
|
||||
@@ -18567,6 +18674,27 @@
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_media_type": {
|
||||
"description": "WorkspaceFileMediaType is the best-effort declared MIME type.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_name": {
|
||||
"description": "WorkspaceFileName is the sanitized basename of a workspace upload.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_path": {
|
||||
"description": "WorkspaceFilePath is the absolute path of a workspace upload.\nThe bytes live on the workspace filesystem; only metadata is\npersisted on the message.",
|
||||
"type": "string"
|
||||
},
|
||||
"workspace_file_size": {
|
||||
"description": "WorkspaceFileSize is the byte size of a workspace upload.",
|
||||
"type": "integer"
|
||||
},
|
||||
"workspace_file_workspace_id": {
|
||||
"description": "WorkspaceFileWorkspaceID identifies the workspace whose\nfilesystem holds the uploaded bytes. References are only\nreadable while the chat stays bound to that workspace.",
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -18582,6 +18710,7 @@
|
||||
"file-reference",
|
||||
"context-file",
|
||||
"skill",
|
||||
"workspace-file-reference",
|
||||
"hook-context",
|
||||
"hook-notice"
|
||||
],
|
||||
@@ -18595,6 +18724,7 @@
|
||||
"ChatMessagePartTypeFileReference",
|
||||
"ChatMessagePartTypeContextFile",
|
||||
"ChatMessagePartTypeSkill",
|
||||
"ChatMessagePartTypeWorkspaceFileReference",
|
||||
"ChatMessagePartTypeHookContext",
|
||||
"ChatMessagePartTypeHookNotice"
|
||||
]
|
||||
@@ -28218,6 +28348,32 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"codersdk.UploadChatWorkspaceFileResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"media_type": {
|
||||
"description": "MediaType is the client-declared content type for display.",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name is the final basename of the uploaded file.",
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"description": "Path is the absolute path of the file on the workspace.",
|
||||
"type": "string"
|
||||
},
|
||||
"size": {
|
||||
"description": "Size is the number of bytes written to the workspace.",
|
||||
"type": "integer"
|
||||
},
|
||||
"workspace_id": {
|
||||
"description": "WorkspaceID is the workspace whose filesystem received the\nbytes. Message parts referencing this upload must carry it.",
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
},
|
||||
"codersdk.UploadResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -86,6 +86,10 @@ func (api *API) registerChatAPIRoutes(r chi.Router, apiKeyMiddleware func(http.H
|
||||
r.Post("/tool-results", api.postChatToolResults)
|
||||
r.Post("/title/propose", api.proposeChatTitle)
|
||||
r.Get("/diff", api.getChatDiffContents)
|
||||
r.With(
|
||||
httpmw.RateLimit(api.FilesRateLimit, time.Minute),
|
||||
api.chatWorkspaceUploadMiddleware,
|
||||
).Post("/workspace-files", api.postChatWorkspaceFile)
|
||||
r.Put("/context", api.refreshChatContext)
|
||||
r.Route("/queue/{queuedMessage}", func(r chi.Router) {
|
||||
r.Delete("/", api.deleteChatQueuedMessage)
|
||||
|
||||
@@ -1040,6 +1040,13 @@ func New(options *Options) *API {
|
||||
}
|
||||
|
||||
wsMetrics := httpmw.NewWSMetrics(options.PrometheusRegistry)
|
||||
api.chatWorkspaceUploadsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "coderd",
|
||||
Subsystem: "chat",
|
||||
Name: "workspace_upload_total",
|
||||
Help: "Total chat workspace file uploads by HTTP response status.",
|
||||
}, []string{"status"})
|
||||
options.PrometheusRegistry.MustRegister(api.chatWorkspaceUploadsTotal)
|
||||
api.wsWatcher = httpapi.NewWSWatcher(options.Clock, wsMetrics.RecordProbe)
|
||||
|
||||
api.workspaceAppServer = workspaceapps.NewServer(workspaceapps.ServerOptions{
|
||||
@@ -2249,6 +2256,8 @@ type API struct {
|
||||
workspaceAgentRPCMetrics *WorkspaceAgentRPCMetrics
|
||||
wsWatcher *httpapi.WSWatcher
|
||||
|
||||
chatWorkspaceUploadsTotal *prometheus.CounterVec
|
||||
|
||||
Acquirer *provisionerdserver.Acquirer
|
||||
// dbRolluper rolls up template usage stats from raw agent and app
|
||||
// stats. This is used to provide insights in the WebUI.
|
||||
|
||||
+533
-12
@@ -14,11 +14,14 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -34,6 +37,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/db2sdk"
|
||||
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
||||
"github.com/coder/coder/v2/coderd/database/dbtime"
|
||||
dbpubsub "github.com/coder/coder/v2/coderd/database/pubsub"
|
||||
"github.com/coder/coder/v2/coderd/dynamicparameters"
|
||||
"github.com/coder/coder/v2/coderd/externalauth"
|
||||
@@ -48,6 +52,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/searchquery"
|
||||
"github.com/coder/coder/v2/coderd/tracing"
|
||||
"github.com/coder/coder/v2/coderd/workspaceapps"
|
||||
"github.com/coder/coder/v2/coderd/workspacestats"
|
||||
"github.com/coder/coder/v2/coderd/wsbuilder"
|
||||
"github.com/coder/coder/v2/coderd/x/agenthooks/dispatch"
|
||||
"github.com/coder/coder/v2/coderd/x/chatd"
|
||||
@@ -62,7 +67,9 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/x/chatfiles"
|
||||
"github.com/coder/coder/v2/coderd/x/gitsync"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/codersdk/wsjson"
|
||||
"github.com/coder/quartz"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
@@ -1917,11 +1924,37 @@ func (api *API) authorizeChatWorkspaceExec(
|
||||
r *http.Request,
|
||||
chat database.Chat,
|
||||
noWorkspaceMessage string,
|
||||
) (database.Workspace, bool) {
|
||||
return api.authorizeChatWorkspaceExecWithStatus(
|
||||
rw,
|
||||
r,
|
||||
chat,
|
||||
http.StatusBadRequest,
|
||||
noWorkspaceMessage,
|
||||
http.StatusBadRequest,
|
||||
codersdk.ChatGitWatchWorkspaceNotFoundMessage,
|
||||
)
|
||||
}
|
||||
|
||||
// authorizeChatWorkspaceExecWithStatus is authorizeChatWorkspaceExec
|
||||
// with caller-chosen statuses and messages for the no-workspace and
|
||||
// workspace-not-found failures. The workspace upload endpoint reports
|
||||
// these as 409 conflicts while the stream endpoints use 400.
|
||||
//
|
||||
//nolint:revive // HTTP handler writes to ResponseWriter.
|
||||
func (api *API) authorizeChatWorkspaceExecWithStatus(
|
||||
rw http.ResponseWriter,
|
||||
r *http.Request,
|
||||
chat database.Chat,
|
||||
noWorkspaceStatus int,
|
||||
noWorkspaceMessage string,
|
||||
notFoundStatus int,
|
||||
notFoundMessage string,
|
||||
) (database.Workspace, bool) {
|
||||
ctx := r.Context()
|
||||
|
||||
if !chat.WorkspaceID.Valid {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
httpapi.Write(ctx, rw, noWorkspaceStatus, codersdk.Response{
|
||||
Message: noWorkspaceMessage,
|
||||
})
|
||||
return database.Workspace{}, false
|
||||
@@ -1929,8 +1962,8 @@ func (api *API) authorizeChatWorkspaceExec(
|
||||
|
||||
workspace, err := api.Database.GetWorkspaceByID(ctx, chat.WorkspaceID.UUID)
|
||||
if httpapi.Is404Error(err) {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: codersdk.ChatGitWatchWorkspaceNotFoundMessage,
|
||||
httpapi.Write(ctx, rw, notFoundStatus, codersdk.Response{
|
||||
Message: notFoundMessage,
|
||||
})
|
||||
return database.Workspace{}, false
|
||||
}
|
||||
@@ -2704,7 +2737,7 @@ func (api *API) postChatMessages(rw http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
contentBlocks, _, inputError := createChatInputFromParts(ctx, api.Database, req.Content, "content")
|
||||
contentBlocks, _, inputError := createChatInputFromParts(ctx, api.Database, chat.ID, chat.WorkspaceID, req.Content, "content")
|
||||
if inputError != nil {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: inputError.Message,
|
||||
@@ -2938,7 +2971,7 @@ func (api *API) patchChatMessage(rw http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
contentBlocks, _, inputError := createChatInputFromParts(ctx, api.Database, req.Content, "content")
|
||||
contentBlocks, _, inputError := createChatInputFromParts(ctx, api.Database, chat.ID, chat.WorkspaceID, req.Content, "content")
|
||||
if inputError != nil {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: inputError.Message,
|
||||
@@ -6348,12 +6381,7 @@ func (api *API) postChatFile(rw http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Extract filename from Content-Disposition header if provided.
|
||||
var filename string
|
||||
if cd := r.Header.Get("Content-Disposition"); cd != "" {
|
||||
if _, params, err := mime.ParseMediaType(cd); err == nil {
|
||||
filename = params["filename"]
|
||||
}
|
||||
}
|
||||
filename := chatFilenameFromContentDisposition(r.Header.Get("Content-Disposition"))
|
||||
|
||||
r.Body = http.MaxBytesReader(rw, r.Body, codersdk.MaxChatFileSizeBytes)
|
||||
data, err := io.ReadAll(r.Body)
|
||||
@@ -6624,12 +6652,434 @@ func (api *API) serveChatFile(ctx context.Context, rw http.ResponseWriter, chatF
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
chatWorkspaceUploadNoWorkspaceMessage = "Chat has no workspace to upload to."
|
||||
chatWorkspaceUploadWorkspaceNotFoundMessage = "Chat workspace not found."
|
||||
chatWorkspaceUploadWorkspaceDeletedMessage = "Chat workspace was deleted."
|
||||
chatWorkspaceUploadNoAgentsMessage = "Chat workspace has no agents."
|
||||
chatWorkspaceUploadArchivedMessage = "Cannot upload files to an archived chat."
|
||||
chatWorkspaceUploadOwnerOnlyMessage = "Only the chat owner may upload files to a chat's workspace."
|
||||
chatWorkspaceUploadMissingFilenameMessage = "Filename is required."
|
||||
chatWorkspaceUploadNoChatAgentMessage = "No chat-compatible workspace agent found."
|
||||
chatWorkspaceUploadAgentDialTimeout = 30 * time.Second
|
||||
// Transport errors embed the agent's tailnet URL, so they are logged
|
||||
// rather than returned to the client.
|
||||
chatWorkspaceUploadAgentUnreachableDetail = "The workspace agent could not be reached. Check that the workspace agent is connected and retry."
|
||||
)
|
||||
|
||||
func (api *API) chatWorkspaceUploadMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
apiKey := httpmw.APIKey(r)
|
||||
chat := httpmw.ChatParam(r)
|
||||
|
||||
if !api.Authorize(r, policy.ActionUpdate, chat.RBACObject()) {
|
||||
httpapi.ResourceNotFound(rw)
|
||||
return
|
||||
}
|
||||
|
||||
if apiKey.UserID != chat.OwnerID {
|
||||
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{
|
||||
Message: chatWorkspaceUploadOwnerOnlyMessage,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if chat.Archived {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: chatWorkspaceUploadArchivedMessage,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary Upload a file to a chat's workspace
|
||||
// @ID upload-a-file-to-a-chats-workspace
|
||||
// @Security CoderSessionToken
|
||||
// @Accept */*
|
||||
// @Tags Chats
|
||||
// @Produce json
|
||||
// @Param chat path string true "Chat ID" format(uuid)
|
||||
// @Param Content-Disposition header string true "Filename of the file (attachment; filename=...)"
|
||||
// @Param request body string true "Raw file binary data"
|
||||
// @x-apidocgen {"rawBodyFile": "archive.zip"}
|
||||
// @Success 201 {object} codersdk.UploadChatWorkspaceFileResponse
|
||||
// @Failure 400 {object} codersdk.Response
|
||||
// @Failure 403 {object} codersdk.Response
|
||||
// @Failure 409 {object} codersdk.Response
|
||||
// @Failure 429 {object} codersdk.Response
|
||||
// @Failure 500 {object} codersdk.Response
|
||||
// @Failure 502 {object} codersdk.Response
|
||||
// @Router /api/v2/chats/{chat}/workspace-files [post]
|
||||
// @Description Streams the request body into the chat workspace's
|
||||
// @Description upload directory. The request Content-Type header is
|
||||
// @Description recorded as the file's media type. There is no
|
||||
// @Description server-imposed size cap; client cancellation aborts the
|
||||
// @Description stream and the agent leaves no partial target file behind.
|
||||
func (api *API) postChatWorkspaceFile(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
chat := httpmw.ChatParam(r)
|
||||
start := api.Clock.Now()
|
||||
sw := &tracing.StatusWriter{ResponseWriter: rw}
|
||||
rw = sw
|
||||
|
||||
var (
|
||||
workspaceID uuid.UUID
|
||||
agentID uuid.UUID
|
||||
name string
|
||||
body *workspaceUsageReader
|
||||
failure error
|
||||
)
|
||||
defer func() {
|
||||
api.chatWorkspaceUploadsTotal.WithLabelValues(strconv.Itoa(sw.Status)).Inc()
|
||||
if sw.Status < http.StatusBadRequest {
|
||||
return
|
||||
}
|
||||
var bytesRead int64
|
||||
if body != nil {
|
||||
bytesRead = body.bytesRead.Load()
|
||||
}
|
||||
fields := []slog.Field{
|
||||
slog.F("chat_id", chat.ID),
|
||||
slog.F("workspace_id", workspaceID),
|
||||
slog.F("agent_id", agentID),
|
||||
slog.F("owner_id", chat.OwnerID),
|
||||
slog.F("file_name", name),
|
||||
slog.F("bytes_read", bytesRead),
|
||||
slog.F("duration", api.Clock.Since(start)),
|
||||
slog.F("status", sw.Status),
|
||||
}
|
||||
if failure != nil {
|
||||
fields = append(fields, slog.Error(failure))
|
||||
}
|
||||
api.Logger.Warn(ctx, "chat workspace file upload failed", fields...)
|
||||
}()
|
||||
|
||||
workspace, ok := api.authorizeChatWorkspaceExecWithStatus(
|
||||
rw,
|
||||
r,
|
||||
chat,
|
||||
http.StatusConflict,
|
||||
chatWorkspaceUploadNoWorkspaceMessage,
|
||||
http.StatusConflict,
|
||||
chatWorkspaceUploadWorkspaceNotFoundMessage,
|
||||
)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
workspaceID = workspace.ID
|
||||
// Writing files into the workspace filesystem is an SSH-grade
|
||||
// capability. The exec helper also admits app-connect-only
|
||||
// callers (it serves the read-oriented stream endpoints), so
|
||||
// require SSH explicitly, matching validateChatWorkspaceSelection.
|
||||
if !api.Authorize(r, policy.ActionSSH, workspace) {
|
||||
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{
|
||||
Message: chatWorkspaceUploadWorkspaceNotFoundMessage,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
filename := chatFilenameFromContentDisposition(r.Header.Get("Content-Disposition"))
|
||||
sanitizedName, err := chatfiles.SanitizeWorkspaceUploadName(filename)
|
||||
if err != nil {
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: chatWorkspaceUploadMissingFilenameMessage,
|
||||
Detail: "Provide a filename via the Content-Disposition header.",
|
||||
})
|
||||
return
|
||||
}
|
||||
name = sanitizedName
|
||||
|
||||
contentType := chatfiles.BaseMediaType(r.Header.Get("Content-Type"))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
|
||||
if workspace.Deleted {
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: chatWorkspaceUploadWorkspaceDeletedMessage,
|
||||
})
|
||||
return
|
||||
}
|
||||
latestBuild, err := api.Database.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspace.ID)
|
||||
if err != nil {
|
||||
failure = err
|
||||
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
||||
Message: "Internal error fetching workspace build.",
|
||||
Detail: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
job, err := api.Database.GetProvisionerJobByID(ctx, latestBuild.JobID)
|
||||
if err != nil {
|
||||
failure = err
|
||||
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
||||
Message: "Internal error fetching workspace build job.",
|
||||
Detail: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
workspaceStatus := codersdk.ConvertWorkspaceStatus(
|
||||
codersdk.ProvisionerJobStatus(job.JobStatus),
|
||||
codersdk.WorkspaceTransition(latestBuild.Transition),
|
||||
)
|
||||
if workspaceStatus != codersdk.WorkspaceStatusRunning {
|
||||
action := "Start the workspace"
|
||||
if latestBuild.Transition == database.WorkspaceTransitionStart &&
|
||||
(workspaceStatus == codersdk.WorkspaceStatusPending || workspaceStatus == codersdk.WorkspaceStatusStarting) {
|
||||
action = "Wait for the workspace to start"
|
||||
}
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: fmt.Sprintf("Workspace is %s. %s before uploading files.", workspaceStatus, action),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
agents, err := api.Database.GetWorkspaceAgentsInLatestBuildByWorkspaceID(ctx, workspace.ID)
|
||||
if err != nil {
|
||||
failure = err
|
||||
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
|
||||
Message: "Internal error fetching workspace agents.",
|
||||
Detail: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if len(agents) == 0 {
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: chatWorkspaceUploadNoAgentsMessage,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
selectedAgent, err := chatWorkspaceUploadAgent(chat, agents)
|
||||
if err != nil {
|
||||
failure = err
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: chatWorkspaceUploadNoChatAgentMessage,
|
||||
Detail: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
agentID = selectedAgent.ID
|
||||
|
||||
agentStatus := selectedAgent.Status(dbtime.Now(), api.AgentInactiveDisconnectTimeout)
|
||||
if agentStatus.Status != database.WorkspaceAgentStatusConnected {
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: fmt.Sprintf(
|
||||
"Agent status is %q. Start the workspace agent before uploading files.",
|
||||
agentStatus.Status,
|
||||
),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
dialCtx, dialCancel := context.WithTimeout(ctx, chatWorkspaceUploadAgentDialTimeout)
|
||||
defer dialCancel()
|
||||
agentConn, release, err := api.agentProvider.AgentConn(dialCtx, selectedAgent.ID)
|
||||
if err != nil {
|
||||
failure = err
|
||||
// A dial failure is a coderd-to-agent transport problem, the
|
||||
// same class writeWorkspaceAgentUploadError maps to 502.
|
||||
httpapi.Write(ctx, rw, http.StatusBadGateway, codersdk.Response{
|
||||
Message: "Failed to dial workspace agent.",
|
||||
Detail: chatWorkspaceUploadAgentUnreachableDetail,
|
||||
})
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
// Mirror chatd's connection headers so agent-side chat state (e.g.
|
||||
// the git-watch PathStore) attributes this request to the chat.
|
||||
var ancestorIDs []string
|
||||
if chat.ParentChatID.Valid {
|
||||
ancestorIDs = append(ancestorIDs, chat.ParentChatID.UUID.String())
|
||||
}
|
||||
ancestorJSON, err := json.Marshal(ancestorIDs)
|
||||
if err != nil {
|
||||
ancestorJSON = []byte("[]")
|
||||
}
|
||||
agentConn.SetExtraHeaders(http.Header{
|
||||
workspacesdk.CoderChatIDHeader: {chat.ID.String()},
|
||||
workspacesdk.CoderAncestorChatIDsHeader: {string(ancestorJSON)},
|
||||
})
|
||||
|
||||
// Uploads are neither SSH nor app sessions, so nothing else records
|
||||
// them as workspace usage; without this an uncapped upload started
|
||||
// near the autostop deadline could see its workspace stop mid-stream.
|
||||
// The bump runs as chatd like the heartbeat bump: the upload itself
|
||||
// is already authorized, but the requester may hold only SSH rights
|
||||
// on a shared workspace while the bump needs workspace update.
|
||||
//nolint:gocritic // Activity bump for an upload the requester is already authorized to make.
|
||||
bumpCtx := dbauthz.AsChatd(ctx)
|
||||
body = &workspaceUsageReader{
|
||||
r: r.Body,
|
||||
clock: api.Clock,
|
||||
report: func() {
|
||||
api.WorkspaceUsageTracker.Add(workspace.ID)
|
||||
workspacestats.ActivityBumpWorkspace(bumpCtx, api.Logger.Named("activity_bump"), api.Database, workspace.ID, time.Time{}, workspacestats.ActivityBumpReasonChatWorkspaceUpload)
|
||||
},
|
||||
}
|
||||
body.reportNow()
|
||||
|
||||
resp, err := agentConn.UploadChatFile(ctx, workspacesdk.UploadChatFileRequest{
|
||||
ChatID: chat.ID.String(),
|
||||
Name: name,
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
failure = err
|
||||
writeWorkspaceAgentUploadError(ctx, rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpapi.Write(ctx, rw, http.StatusCreated, codersdk.UploadChatWorkspaceFileResponse{
|
||||
Path: resp.Path,
|
||||
Name: resp.Name,
|
||||
Size: resp.Size,
|
||||
MediaType: contentType,
|
||||
WorkspaceID: workspace.ID,
|
||||
})
|
||||
}
|
||||
|
||||
// chatWorkspaceUploadAgent prefers the chat's bound agent when it is
|
||||
// still part of the latest build so uploads land on the same agent the
|
||||
// generation path uses. Otherwise it falls back to the deterministic
|
||||
// chat agent selection without persisting a binding; binding remains a
|
||||
// generation-path concern, and determinism makes both converge.
|
||||
func chatWorkspaceUploadAgent(chat database.Chat, agents []database.WorkspaceAgent) (database.WorkspaceAgent, error) {
|
||||
if chat.AgentID.Valid {
|
||||
for _, agent := range agents {
|
||||
if agent.ID == chat.AgentID.UUID {
|
||||
return agent, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return agentselect.FindChatAgent(agents)
|
||||
}
|
||||
|
||||
// chatWorkspaceUploadUsageInterval bounds how often a streaming upload
|
||||
// records workspace usage; chatd heartbeats at the same cadence.
|
||||
const chatWorkspaceUploadUsageInterval = 30 * time.Second
|
||||
|
||||
// workspaceUsageReader reports workspace usage while an upload body
|
||||
// streams so long uploads keep extending the autostop deadline.
|
||||
type workspaceUsageReader struct {
|
||||
r io.Reader
|
||||
clock quartz.Clock
|
||||
report func()
|
||||
lastReport time.Time
|
||||
// bytesRead is atomic because the HTTP transport may still be
|
||||
// reading the body when the handler logs a failed upload.
|
||||
bytesRead atomic.Int64
|
||||
}
|
||||
|
||||
func (w *workspaceUsageReader) reportNow() {
|
||||
w.lastReport = w.clock.Now()
|
||||
w.report()
|
||||
}
|
||||
|
||||
func (w *workspaceUsageReader) Read(p []byte) (int, error) {
|
||||
n, err := w.r.Read(p)
|
||||
w.bytesRead.Add(int64(n))
|
||||
if n > 0 && w.clock.Since(w.lastReport) >= chatWorkspaceUploadUsageInterval {
|
||||
w.reportNow()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func writeWorkspaceAgentUploadError(ctx context.Context, rw http.ResponseWriter, err error) {
|
||||
var sdkErr *codersdk.Error
|
||||
if errors.As(err, &sdkErr) && sdkErr.StatusCode() != 0 {
|
||||
// The upload handler never answers 404 itself, so a 404 means
|
||||
// the workspace runs an agent from before this endpoint existed
|
||||
// (coderd upgraded while the workspace kept running).
|
||||
if sdkErr.StatusCode() == http.StatusNotFound {
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: "The workspace agent does not support chat file uploads. Restart the workspace to update its agent, then retry.",
|
||||
})
|
||||
return
|
||||
}
|
||||
httpapi.Write(ctx, rw, sdkErr.StatusCode(), sdkErr.Response)
|
||||
return
|
||||
}
|
||||
httpapi.Write(ctx, rw, http.StatusBadGateway, codersdk.Response{
|
||||
Message: "Failed to upload file to workspace agent.",
|
||||
Detail: chatWorkspaceUploadAgentUnreachableDetail,
|
||||
})
|
||||
}
|
||||
|
||||
func chatFilenameFromContentDisposition(contentDisposition string) string {
|
||||
if contentDisposition == "" {
|
||||
return ""
|
||||
}
|
||||
_, params, err := mime.ParseMediaType(contentDisposition)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return params["filename"]
|
||||
}
|
||||
|
||||
// maxWorkspaceFileReferencePathBytes bounds persisted workspace file
|
||||
// reference paths.
|
||||
const maxWorkspaceFileReferencePathBytes = 4096
|
||||
|
||||
// normalizeWorkspaceFileReference reports whether a client-supplied
|
||||
// workspace file reference plausibly points at a file uploaded for
|
||||
// this chat and returns the cleaned path to persist. The agent home
|
||||
// directory is not known to coderd, so validation is limited to an
|
||||
// absolute path tail scoped by chat ID and a matching basename.
|
||||
func normalizeWorkspaceFileReference(chatID uuid.UUID, filePath, name string) (string, bool) {
|
||||
if chatID == uuid.Nil || len(filePath) > maxWorkspaceFileReferencePathBytes {
|
||||
return "", false
|
||||
}
|
||||
// Control characters (including NUL, which cannot be persisted)
|
||||
// never appear in agent-produced paths or names.
|
||||
if strings.ContainsFunc(filePath, unicode.IsControl) || strings.ContainsFunc(name, unicode.IsControl) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
normalizedPath := path.Clean(strings.ReplaceAll(strings.TrimSpace(filePath), `\`, "/"))
|
||||
normalizedName := strings.ReplaceAll(strings.TrimSpace(name), `\`, "/")
|
||||
if normalizedPath == "." || normalizedName == "." || normalizedName == "" {
|
||||
return "", false
|
||||
}
|
||||
if path.Base(normalizedName) != normalizedName || path.Base(normalizedPath) != normalizedName {
|
||||
return "", false
|
||||
}
|
||||
windowsPath := isWindowsAbsPath(normalizedPath)
|
||||
if !path.IsAbs(normalizedPath) && !windowsPath {
|
||||
return "", false
|
||||
}
|
||||
|
||||
marker := "/" + strings.Trim(chatfiles.WorkspaceChatsDir, "/") + "/" +
|
||||
chatID.String() + "/" + chatfiles.WorkspaceUploadFilesSubdir + "/"
|
||||
if !strings.HasSuffix(normalizedPath, marker+normalizedName) {
|
||||
return "", false
|
||||
}
|
||||
if windowsPath {
|
||||
return strings.ReplaceAll(normalizedPath, "/", `\`), true
|
||||
}
|
||||
return normalizedPath, true
|
||||
}
|
||||
|
||||
func isWindowsAbsPath(p string) bool {
|
||||
return len(p) >= 3 && p[1] == ':' && p[2] == '/' &&
|
||||
(('a' <= p[0] && p[0] <= 'z') || ('A' <= p[0] && p[0] <= 'Z'))
|
||||
}
|
||||
|
||||
func createChatInputFromRequest(ctx context.Context, db database.Store, req codersdk.CreateChatRequest) (
|
||||
[]codersdk.ChatMessagePart,
|
||||
string,
|
||||
*codersdk.Response,
|
||||
) {
|
||||
content, pasteData, inputError := createChatInputFromParts(ctx, db, req.Content, "content")
|
||||
// Chat creation has no chat ID yet, so workspace-file-reference
|
||||
// parts are rejected (they require an existing chat's uploads).
|
||||
content, pasteData, inputError := createChatInputFromParts(ctx, db, uuid.Nil, uuid.NullUUID{}, req.Content, "content")
|
||||
if inputError != nil {
|
||||
return nil, "", inputError
|
||||
}
|
||||
@@ -6654,6 +7104,8 @@ func createChatInputFromRequest(ctx context.Context, db database.Store, req code
|
||||
func createChatInputFromParts(
|
||||
ctx context.Context,
|
||||
db database.Store,
|
||||
chatID uuid.UUID,
|
||||
chatWorkspaceID uuid.NullUUID,
|
||||
parts []codersdk.ChatInputPart,
|
||||
fieldName string,
|
||||
) ([]codersdk.ChatMessagePart, map[uuid.UUID][]byte, *codersdk.Response) {
|
||||
@@ -6726,6 +7178,75 @@ func createChatInputFromParts(
|
||||
}
|
||||
}
|
||||
content = append(content, codersdk.ChatMessageFileReference(part.FileName, part.StartLine, part.EndLine, part.Content))
|
||||
case string(codersdk.ChatInputPartTypeWorkspaceFileReference):
|
||||
if strings.TrimSpace(part.WorkspaceFilePath) == "" {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_path is required for workspace-file-reference.", fieldName, i),
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(part.WorkspaceFileName) == "" {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_name is required for workspace-file-reference.", fieldName, i),
|
||||
}
|
||||
}
|
||||
if part.WorkspaceFileSize < 0 {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_size must be non-negative.", fieldName, i),
|
||||
}
|
||||
}
|
||||
if chatID == uuid.Nil {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace-file-reference requires an existing chat.", fieldName, i),
|
||||
}
|
||||
}
|
||||
// The sanitizer is idempotent, so every name returned by the
|
||||
// upload endpoint passes unchanged.
|
||||
if sanitized, err := chatfiles.SanitizeWorkspaceUploadName(part.WorkspaceFileName); err != nil || sanitized != part.WorkspaceFileName {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_name must be a name returned by the workspace file upload endpoint.", fieldName, i),
|
||||
}
|
||||
}
|
||||
workspaceFilePath, ok := normalizeWorkspaceFileReference(chatID, part.WorkspaceFilePath, part.WorkspaceFileName)
|
||||
if !ok {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_path must reference a file uploaded to this chat.", fieldName, i),
|
||||
}
|
||||
}
|
||||
if strings.ContainsRune(part.WorkspaceFileMediaType, 0) {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_media_type must not contain NUL bytes.", fieldName, i),
|
||||
}
|
||||
}
|
||||
// The referenced bytes live in one specific workspace's
|
||||
// filesystem. Reject references from a workspace other
|
||||
// than the chat's current binding: after a rebind the
|
||||
// path is unreadable for the bound agent.
|
||||
if part.WorkspaceFileWorkspaceID == uuid.Nil {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_workspace_id is required for workspace-file-reference.", fieldName, i),
|
||||
}
|
||||
}
|
||||
if !chatWorkspaceID.Valid || chatWorkspaceID.UUID != part.WorkspaceFileWorkspaceID {
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
Detail: fmt.Sprintf("%s[%d].workspace_file_workspace_id must match the chat's bound workspace. Re-upload the file to the current workspace.", fieldName, i),
|
||||
}
|
||||
}
|
||||
content = append(content, codersdk.ChatMessageWorkspaceFileReference(
|
||||
part.WorkspaceFileWorkspaceID,
|
||||
workspaceFilePath,
|
||||
part.WorkspaceFileName,
|
||||
part.WorkspaceFileSize,
|
||||
chatfiles.BaseMediaType(part.WorkspaceFileMediaType),
|
||||
))
|
||||
default:
|
||||
return nil, nil, &codersdk.Response{
|
||||
Message: "Invalid input part.",
|
||||
|
||||
@@ -5,10 +5,14 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
@@ -28,6 +32,7 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/quartz"
|
||||
)
|
||||
|
||||
func TestAuditedChatOperationalSettingWriteNoOpTransactionFailure(t *testing.T) {
|
||||
@@ -713,3 +718,124 @@ func TestIsZeroChatModelCallConfigReasoningModel(t *testing.T) {
|
||||
}
|
||||
require.True(t, isZeroChatModelCallConfig(&codersdk.ChatModelCallConfig{OpenAIConfig: &codersdk.ChatModelOpenAIConfig{}}))
|
||||
}
|
||||
|
||||
func TestWriteWorkspaceAgentUploadError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("AgentStatus", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
res := &http.Response{
|
||||
StatusCode: http.StatusConflict,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"application/json"},
|
||||
},
|
||||
Body: io.NopCloser(strings.NewReader(`{"message":"too many existing files"}`)),
|
||||
}
|
||||
err := codersdk.ReadBodyAsError(res)
|
||||
rw := httptest.NewRecorder()
|
||||
|
||||
writeWorkspaceAgentUploadError(context.Background(), rw, err)
|
||||
|
||||
require.Equal(t, http.StatusConflict, rw.Code)
|
||||
require.Contains(t, rw.Body.String(), "too many existing files")
|
||||
})
|
||||
|
||||
t.Run("OutdatedAgent", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
res := &http.Response{
|
||||
StatusCode: http.StatusNotFound,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"text/plain"},
|
||||
},
|
||||
Body: io.NopCloser(strings.NewReader("404 page not found")),
|
||||
}
|
||||
err := codersdk.ReadBodyAsError(res)
|
||||
rw := httptest.NewRecorder()
|
||||
|
||||
writeWorkspaceAgentUploadError(context.Background(), rw, err)
|
||||
|
||||
require.Equal(t, http.StatusConflict, rw.Code)
|
||||
require.Contains(t, rw.Body.String(), "Restart the workspace")
|
||||
})
|
||||
|
||||
t.Run("TransportError", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rw := httptest.NewRecorder()
|
||||
|
||||
writeWorkspaceAgentUploadError(context.Background(), rw, xerrors.New("dial failed"))
|
||||
|
||||
require.Equal(t, http.StatusBadGateway, rw.Code)
|
||||
require.Contains(t, rw.Body.String(), "Failed to upload file to workspace agent")
|
||||
require.NotContains(t, rw.Body.String(), "dial failed")
|
||||
})
|
||||
}
|
||||
|
||||
func TestChatWorkspaceUploadAgent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
alpha := database.WorkspaceAgent{ID: uuid.New(), Name: "alpha", DisplayOrder: 0}
|
||||
beta := database.WorkspaceAgent{ID: uuid.New(), Name: "beta", DisplayOrder: 1}
|
||||
agents := []database.WorkspaceAgent{beta, alpha}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
agentID uuid.NullUUID
|
||||
want uuid.UUID
|
||||
}{
|
||||
{name: "Unbound", want: alpha.ID},
|
||||
{name: "BoundAgentPreferred", agentID: uuid.NullUUID{UUID: beta.ID, Valid: true}, want: beta.ID},
|
||||
{name: "StaleBindingFallsBack", agentID: uuid.NullUUID{UUID: uuid.New(), Valid: true}, want: alpha.ID},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, err := chatWorkspaceUploadAgent(database.Chat{AgentID: tt.agentID}, agents)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, got.ID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceUsageReader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
clock := quartz.NewMock(t)
|
||||
var reports int
|
||||
reader := &workspaceUsageReader{
|
||||
r: iotest.OneByteReader(strings.NewReader("abcd")),
|
||||
clock: clock,
|
||||
report: func() { reports++ },
|
||||
}
|
||||
reader.reportNow()
|
||||
require.Equal(t, 1, reports)
|
||||
|
||||
buf := make([]byte, 1)
|
||||
read := func() {
|
||||
t.Helper()
|
||||
_, err := reader.Read(buf)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
read()
|
||||
clock.Advance(chatWorkspaceUploadUsageInterval - time.Second)
|
||||
read()
|
||||
require.Equal(t, 1, reports, "reported before the interval elapsed")
|
||||
|
||||
clock.Advance(time.Second)
|
||||
read()
|
||||
require.Equal(t, 2, reports, "did not report once the interval elapsed")
|
||||
|
||||
read()
|
||||
require.Equal(t, 2, reports)
|
||||
require.EqualValues(t, 4, reader.bytesRead.Load())
|
||||
|
||||
clock.Advance(chatWorkspaceUploadUsageInterval)
|
||||
n, err := reader.Read(buf)
|
||||
require.Zero(t, n)
|
||||
require.ErrorIs(t, err, io.EOF)
|
||||
require.Equal(t, 2, reports, "empty reads must not count as usage")
|
||||
}
|
||||
@@ -0,0 +1,940 @@
|
||||
package coderd_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/coder/coder/v2/agent"
|
||||
"github.com/coder/coder/v2/agent/agenttest"
|
||||
"github.com/coder/coder/v2/agent/usershell"
|
||||
"github.com/coder/coder/v2/coderd"
|
||||
"github.com/coder/coder/v2/coderd/coderdtest"
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
||||
"github.com/coder/coder/v2/coderd/database/dbfake"
|
||||
"github.com/coder/coder/v2/coderd/database/dbgen"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/coderd/rbac/policy"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
|
||||
// uploadChatWorkspaceFile bypasses the SDK helper so tests can drive
|
||||
// the endpoint with a raw (or missing) Content-Disposition header that
|
||||
// the helper would otherwise set automatically.
|
||||
func uploadChatWorkspaceFile(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
client *codersdk.ExperimentalClient,
|
||||
chatID, contentDisposition, contentType string,
|
||||
body []byte,
|
||||
) (*http.Response, error) {
|
||||
t.Helper()
|
||||
return client.Request(ctx, http.MethodPost,
|
||||
"/api/v2/chats/"+chatID+"/workspace-files",
|
||||
bytes.NewReader(body),
|
||||
func(r *http.Request) {
|
||||
if contentType != "" {
|
||||
r.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if contentDisposition != "" {
|
||||
r.Header.Set("Content-Disposition", contentDisposition)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func TestNormalizeWorkspaceFileReference(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
chatID := uuid.MustParse("00000000-0000-0000-0000-000000000001")
|
||||
otherChatID := uuid.MustParse("00000000-0000-0000-0000-000000000002")
|
||||
tests := []struct {
|
||||
name string
|
||||
chatID uuid.UUID
|
||||
path string
|
||||
fileName string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "LinuxPath",
|
||||
chatID: chatID,
|
||||
path: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
fileName: "data.csv",
|
||||
want: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
},
|
||||
{
|
||||
name: "WindowsPath",
|
||||
chatID: chatID,
|
||||
path: `C:\Users\coder\.coder\chats\00000000-0000-0000-0000-000000000001\files\data.csv`,
|
||||
fileName: "data.csv",
|
||||
want: `C:\Users\coder\.coder\chats\00000000-0000-0000-0000-000000000001\files\data.csv`,
|
||||
},
|
||||
{
|
||||
name: "NilChatID",
|
||||
chatID: uuid.Nil,
|
||||
path: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
fileName: "data.csv",
|
||||
},
|
||||
{
|
||||
name: "Traversal",
|
||||
chatID: chatID,
|
||||
path: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/../data.csv",
|
||||
fileName: "data.csv",
|
||||
},
|
||||
{
|
||||
name: "MismatchedChatID",
|
||||
chatID: otherChatID,
|
||||
path: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
fileName: "data.csv",
|
||||
},
|
||||
{
|
||||
name: "NULInPath",
|
||||
chatID: chatID,
|
||||
path: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data\x00.csv",
|
||||
fileName: "data\x00.csv",
|
||||
},
|
||||
{
|
||||
name: "NameWithSeparator",
|
||||
chatID: chatID,
|
||||
path: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
fileName: "nested/data.csv",
|
||||
},
|
||||
{
|
||||
name: "UncleanPrefixIsCleaned",
|
||||
chatID: chatID,
|
||||
path: " /home/coder/./tmp/../.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv ",
|
||||
fileName: "data.csv",
|
||||
want: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
},
|
||||
{
|
||||
name: "WindowsUncleanPrefixIsCleaned",
|
||||
chatID: chatID,
|
||||
path: `C:\Users\coder\tmp\..\.coder\chats\00000000-0000-0000-0000-000000000001\files\data.csv`,
|
||||
fileName: "data.csv",
|
||||
want: `C:\Users\coder\.coder\chats\00000000-0000-0000-0000-000000000001\files\data.csv`,
|
||||
},
|
||||
{
|
||||
name: "NewlineInPrefix",
|
||||
chatID: chatID,
|
||||
path: "/home/co\nder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
fileName: "data.csv",
|
||||
},
|
||||
{
|
||||
name: "PathTooLong",
|
||||
chatID: chatID,
|
||||
path: "/" + strings.Repeat("a", 4096) + "/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
fileName: "data.csv",
|
||||
},
|
||||
{
|
||||
name: "ArbitraryAbsolutePath",
|
||||
chatID: chatID,
|
||||
path: "/etc/passwd",
|
||||
fileName: "passwd",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, ok := coderd.NormalizeWorkspaceFileReference(tt.chatID, tt.path, tt.fileName)
|
||||
require.Equal(t, tt.want != "", ok)
|
||||
require.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatWorkspaceFilePartValidation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
part codersdk.ChatInputPart
|
||||
detail string
|
||||
}{
|
||||
{
|
||||
name: "InitialChatCreationRejectsWorkspaceReference",
|
||||
part: codersdk.ChatInputPart{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/data.csv",
|
||||
WorkspaceFileName: "data.csv",
|
||||
WorkspaceFileSize: 42,
|
||||
},
|
||||
detail: "content[0].workspace-file-reference requires an existing chat.",
|
||||
},
|
||||
{
|
||||
name: "MissingPath",
|
||||
part: codersdk.ChatInputPart{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFileName: "data.csv",
|
||||
WorkspaceFileSize: 42,
|
||||
},
|
||||
detail: "content[0].workspace_file_path is required for workspace-file-reference.",
|
||||
},
|
||||
{
|
||||
name: "MissingName",
|
||||
part: codersdk.ChatInputPart{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/chat-id/files/data.csv",
|
||||
WorkspaceFileSize: 42,
|
||||
},
|
||||
detail: "content[0].workspace_file_name is required for workspace-file-reference.",
|
||||
},
|
||||
{
|
||||
name: "NegativeSize",
|
||||
part: codersdk.ChatInputPart{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/chat-id/files/data.csv",
|
||||
WorkspaceFileName: "data.csv",
|
||||
WorkspaceFileSize: -1,
|
||||
},
|
||||
detail: "content[0].workspace_file_size must be non-negative.",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client := newChatClient(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
_, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{tt.part},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "Invalid input part.", sdkErr.Message)
|
||||
require.Equal(t, tt.detail, sdkErr.Detail)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatMessageWorkspaceFilePartRejectsInvalidPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client := newChatClient(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "hello"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: "/etc/passwd",
|
||||
WorkspaceFileName: "passwd",
|
||||
WorkspaceFileSize: 42,
|
||||
WorkspaceFileMediaType: "text/plain",
|
||||
},
|
||||
},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "Invalid input part.", sdkErr.Message)
|
||||
require.Equal(t, "content[0].workspace_file_path must reference a file uploaded to this chat.", sdkErr.Detail)
|
||||
}
|
||||
|
||||
func TestCreateChatMessageWorkspaceFileWorkspaceValidation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
validPart := func(chatID uuid.UUID) codersdk.ChatInputPart {
|
||||
return codersdk.ChatInputPart{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/" + chatID.String() + "/files/data.csv",
|
||||
WorkspaceFileName: "data.csv",
|
||||
WorkspaceFileSize: 42,
|
||||
WorkspaceFileMediaType: "text/csv",
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("MissingWorkspaceID", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client := newChatClient(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "hello"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{validPart(chat.ID)},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "Invalid input part.", sdkErr.Message)
|
||||
require.Equal(t, "content[0].workspace_file_workspace_id is required for workspace-file-reference.", sdkErr.Detail)
|
||||
})
|
||||
|
||||
t.Run("WorkspaceMismatch", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
WorkspaceID: &workspaceBuild.Workspace.ID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "hello"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// References uploaded to a different workspace than the chat's
|
||||
// current binding are unreadable for the bound agent.
|
||||
part := validPart(chat.ID)
|
||||
part.WorkspaceFileWorkspaceID = uuid.New()
|
||||
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{part},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "Invalid input part.", sdkErr.Message)
|
||||
require.Equal(t, "content[0].workspace_file_workspace_id must match the chat's bound workspace. Re-upload the file to the current workspace.", sdkErr.Detail)
|
||||
})
|
||||
|
||||
t.Run("UnboundChat", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client := newChatClient(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "hello"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
part := validPart(chat.ID)
|
||||
part.WorkspaceFileWorkspaceID = uuid.New()
|
||||
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{part},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "Invalid input part.", sdkErr.Message)
|
||||
require.Equal(t, "content[0].workspace_file_workspace_id must match the chat's bound workspace. Re-upload the file to the current workspace.", sdkErr.Detail)
|
||||
})
|
||||
|
||||
newBoundChat := func(ctx context.Context, t *testing.T) (*codersdk.ExperimentalClient, codersdk.Chat) {
|
||||
t.Helper()
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
WorkspaceID: &workspaceBuild.Workspace.ID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "hello"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return client, chat
|
||||
}
|
||||
|
||||
t.Run("UnsanitizedName", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, chat := newBoundChat(ctx, t)
|
||||
|
||||
for _, name := range []string{" data.csv", "da\u202eta.csv", "da|ta.csv"} {
|
||||
part := validPart(chat.ID)
|
||||
part.WorkspaceFileWorkspaceID = *chat.WorkspaceID
|
||||
part.WorkspaceFileName = name
|
||||
part.WorkspaceFilePath = "/home/coder/.coder/chats/" + chat.ID.String() + "/files/" + name
|
||||
_, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{part},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "content[0].workspace_file_name must be a name returned by the workspace file upload endpoint.", sdkErr.Detail, "name %q", name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PersistsNormalizedReference", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, chat := newBoundChat(ctx, t)
|
||||
|
||||
part := validPart(chat.ID)
|
||||
part.WorkspaceFileWorkspaceID = *chat.WorkspaceID
|
||||
part.WorkspaceFilePath = " /home/coder/./tmp/../.coder/chats/" + chat.ID.String() + "/files/data.csv "
|
||||
part.WorkspaceFileMediaType = "Text/CSV; charset=utf-8"
|
||||
resp, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{part},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var parts []codersdk.ChatMessagePart
|
||||
if resp.Queued {
|
||||
require.NotNil(t, resp.QueuedMessage)
|
||||
parts = resp.QueuedMessage.Content
|
||||
} else {
|
||||
require.NotNil(t, resp.Message)
|
||||
parts = resp.Message.Content
|
||||
}
|
||||
require.Contains(t, parts, codersdk.ChatMessageWorkspaceFileReference(
|
||||
*chat.WorkspaceID,
|
||||
"/home/coder/.coder/chats/"+chat.ID.String()+"/files/data.csv",
|
||||
"data.csv",
|
||||
42,
|
||||
"text/csv",
|
||||
))
|
||||
})
|
||||
|
||||
t.Run("EditSharesValidation", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, chat := newBoundChat(ctx, t)
|
||||
|
||||
messages, err := client.GetChatMessages(ctx, chat.ID, nil)
|
||||
require.NoError(t, err)
|
||||
var userMessageID int64
|
||||
for _, message := range messages.Messages {
|
||||
if message.Role == codersdk.ChatMessageRoleUser {
|
||||
userMessageID = message.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
require.NotZero(t, userMessageID)
|
||||
|
||||
// Edits go through the same validation as sends, so a reference
|
||||
// from another workspace is rejected.
|
||||
stale := validPart(chat.ID)
|
||||
stale.WorkspaceFileWorkspaceID = uuid.New()
|
||||
_, err = client.EditChatMessage(ctx, chat.ID, userMessageID, codersdk.EditChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{stale},
|
||||
})
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Equal(t, "content[0].workspace_file_workspace_id must match the chat's bound workspace. Re-upload the file to the current workspace.", sdkErr.Detail)
|
||||
|
||||
current := validPart(chat.ID)
|
||||
current.WorkspaceFileWorkspaceID = *chat.WorkspaceID
|
||||
current.WorkspaceFilePath = "/home/coder/./.coder/chats/" + chat.ID.String() + "/files/data.csv"
|
||||
edited, err := client.EditChatMessage(ctx, chat.ID, userMessageID, codersdk.EditChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{current},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, edited.Message.Content, codersdk.ChatMessageWorkspaceFileReference(
|
||||
*chat.WorkspaceID,
|
||||
"/home/coder/.coder/chats/"+chat.ID.String()+"/files/data.csv",
|
||||
"data.csv",
|
||||
42,
|
||||
"text/csv",
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
// homeDirEnvInfo pins the agent's home directory so upload tests can run
|
||||
// in parallel instead of overriding HOME for the whole process.
|
||||
type homeDirEnvInfo struct {
|
||||
usershell.SystemEnvInfo
|
||||
home string
|
||||
}
|
||||
|
||||
func (e homeDirEnvInfo) HomeDir() (string, error) { return e.home, nil }
|
||||
|
||||
// startChatUploadAgent connects a real agent with its own home directory
|
||||
// and returns that directory.
|
||||
func startChatUploadAgent(t *testing.T, client *codersdk.ExperimentalClient, workspaceBuild dbfake.WorkspaceResponse) string {
|
||||
t.Helper()
|
||||
home := t.TempDir()
|
||||
_ = agenttest.New(t, client.URL, workspaceBuild.AgentToken, func(o *agent.Options) {
|
||||
o.EnvInfo = homeDirEnvInfo{home: home}
|
||||
})
|
||||
coderdtest.NewWorkspaceAgentWaiter(t, client.Client, workspaceBuild.Workspace.ID).WaitFor(coderdtest.AgentsReady)
|
||||
return home
|
||||
}
|
||||
|
||||
func createBoundChat(ctx context.Context, t *testing.T, client *codersdk.ExperimentalClient, organizationID, workspaceID uuid.UUID) codersdk.Chat {
|
||||
t.Helper()
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: organizationID,
|
||||
WorkspaceID: &workspaceID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "upload a file"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return chat
|
||||
}
|
||||
|
||||
func TestPostChatWorkspaceFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("Success", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db, api := newChatClientWithAPIAndDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
home := startChatUploadAgent(t, client, workspaceBuild)
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
payload := bytes.Repeat([]byte{0x50, 0x4b}, 16)
|
||||
resp, err := client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "archive.zip", bytes.NewReader(payload))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "archive.zip", resp.Name)
|
||||
require.Equal(t, int64(len(payload)), resp.Size)
|
||||
require.Equal(t, "application/zip", resp.MediaType)
|
||||
require.Equal(t, workspaceBuild.Workspace.ID, resp.WorkspaceID)
|
||||
require.True(t, strings.HasPrefix(resp.Path, home), "expected path under home, got %q (home=%q)", resp.Path, home)
|
||||
|
||||
bytesOnDisk, err := os.ReadFile(resp.Path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, payload, bytesOnDisk)
|
||||
|
||||
messageResp, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{
|
||||
Type: codersdk.ChatInputPartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: resp.Path,
|
||||
WorkspaceFileName: resp.Name,
|
||||
WorkspaceFileSize: resp.Size,
|
||||
WorkspaceFileMediaType: resp.MediaType,
|
||||
WorkspaceFileWorkspaceID: resp.WorkspaceID,
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var messageParts []codersdk.ChatMessagePart
|
||||
if messageResp.Queued {
|
||||
require.NotNil(t, messageResp.QueuedMessage)
|
||||
messageParts = messageResp.QueuedMessage.Content
|
||||
} else {
|
||||
require.NotNil(t, messageResp.Message)
|
||||
messageParts = messageResp.Message.Content
|
||||
}
|
||||
require.Contains(t, messageParts, codersdk.ChatMessageWorkspaceFileReference(
|
||||
resp.WorkspaceID,
|
||||
resp.Path,
|
||||
resp.Name,
|
||||
resp.Size,
|
||||
resp.MediaType,
|
||||
))
|
||||
|
||||
// Archiving requires the chat generation to settle first.
|
||||
coderdtest.WaitForChatSettled(ctx, t, api, chat.ID)
|
||||
archived := true
|
||||
err = client.UpdateChat(ctx, chat.ID, codersdk.UpdateChatRequest{
|
||||
Archived: &archived,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = os.Stat(resp.Path)
|
||||
require.NoError(t, err, "archive should not remove workspace files")
|
||||
})
|
||||
|
||||
t.Run("ConcurrentSameName", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
_ = startChatUploadAgent(t, client, workspaceBuild)
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
// Same-name uploads racing each other must land on distinct
|
||||
// paths instead of overwriting one another.
|
||||
payloads := [][]byte{[]byte("first"), []byte("second")}
|
||||
results := make([]codersdk.UploadChatWorkspaceFileResponse, len(payloads))
|
||||
var eg errgroup.Group
|
||||
for i, payload := range payloads {
|
||||
eg.Go(func() error {
|
||||
resp, err := client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "archive.zip", bytes.NewReader(payload))
|
||||
results[i] = resp
|
||||
return err
|
||||
})
|
||||
}
|
||||
require.NoError(t, eg.Wait())
|
||||
|
||||
require.ElementsMatch(t, []string{"archive.zip", "archive_2.zip"}, []string{results[0].Name, results[1].Name})
|
||||
for i, result := range results {
|
||||
bytesOnDisk, err := os.ReadFile(result.Path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, payloads[i], bytesOnDisk)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RFC5987Filename", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
_ = startChatUploadAgent(t, client, workspaceBuild)
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
res, err := uploadChatWorkspaceFile(ctx, t, client, chat.ID.String(),
|
||||
"attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf", "application/pdf", []byte("%PDF"))
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
require.Equal(t, http.StatusCreated, res.StatusCode)
|
||||
var uploaded codersdk.UploadChatWorkspaceFileResponse
|
||||
require.NoError(t, json.NewDecoder(res.Body).Decode(&uploaded))
|
||||
require.Equal(t, "r\u00e9sum\u00e9.pdf", uploaded.Name)
|
||||
require.Equal(t, uploaded.Name, filepath.Base(uploaded.Path))
|
||||
})
|
||||
|
||||
t.Run("MissingFilename", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
res, err := uploadChatWorkspaceFile(ctx, t, client, chat.ID.String(), "", "application/zip", []byte("PK"))
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
require.Equal(t, http.StatusBadRequest, res.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("NoWorkspace", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client := newChatClient(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "no workspace"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusConflict)
|
||||
require.Contains(t, sdkErr.Message, "no workspace")
|
||||
})
|
||||
|
||||
t.Run("RateLimited", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client := newChatClient(t, func(o *coderdtest.Options) {
|
||||
o.FilesRateLimit = 1
|
||||
})
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "rate limited"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
requireSDKError(t, err, http.StatusConflict)
|
||||
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
requireSDKError(t, err, http.StatusTooManyRequests)
|
||||
})
|
||||
|
||||
t.Run("NoAgents", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).Do()
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
_, err := client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusConflict)
|
||||
require.Equal(t, "Chat workspace has no agents.", sdkErr.Message)
|
||||
})
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
build func(dbfake.WorkspaceBuildBuilder) dbfake.WorkspaceBuildBuilder
|
||||
message string
|
||||
}{
|
||||
{
|
||||
name: "WorkspaceStopped",
|
||||
build: func(b dbfake.WorkspaceBuildBuilder) dbfake.WorkspaceBuildBuilder {
|
||||
return b.Seed(database.WorkspaceBuild{Transition: database.WorkspaceTransitionStop})
|
||||
},
|
||||
message: "Workspace is stopped. Start the workspace before uploading files.",
|
||||
},
|
||||
{
|
||||
name: "WorkspaceStarting",
|
||||
build: func(b dbfake.WorkspaceBuildBuilder) dbfake.WorkspaceBuildBuilder {
|
||||
return b.Starting()
|
||||
},
|
||||
message: "Workspace is starting. Wait for the workspace to start before uploading files.",
|
||||
},
|
||||
{
|
||||
name: "WorkspacePending",
|
||||
build: func(b dbfake.WorkspaceBuildBuilder) dbfake.WorkspaceBuildBuilder {
|
||||
return b.Pending()
|
||||
},
|
||||
message: "Workspace is pending. Wait for the workspace to start before uploading files.",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := tc.build(dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent()).Do()
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
_, err := client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusConflict)
|
||||
require.Equal(t, tc.message, sdkErr.Message)
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("WorkspaceDeleted", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
err := db.UpdateWorkspaceDeletedByID(dbauthz.AsSystemRestricted(ctx), database.UpdateWorkspaceDeletedByIDParams{
|
||||
ID: workspaceBuild.Workspace.ID,
|
||||
Deleted: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusConflict)
|
||||
require.Equal(t, "Chat workspace was deleted.", sdkErr.Message)
|
||||
})
|
||||
|
||||
t.Run("NoConnectedAgent", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
// dbfake.WorkspaceBuild + WithAgent records an agent in the
|
||||
// database but never connects it, so the handler should see a
|
||||
// disconnected agent.
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
_, err := client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusConflict)
|
||||
require.Contains(t, sdkErr.Message, "Agent status")
|
||||
})
|
||||
|
||||
t.Run("SharedWorkspaceRequiresSSH", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
memberClientRaw, member := coderdtest.CreateAnotherUser(t, client.Client, firstUser.OrganizationID)
|
||||
memberClient := codersdk.NewExperimentalClient(memberClientRaw)
|
||||
aclWith := func(actions ...policy.Action) database.WorkspaceACL {
|
||||
return database.WorkspaceACL{member.ID.String(): {Permissions: actions}}
|
||||
}
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
UserACL: aclWith(policy.ActionRead, policy.ActionSSH, policy.ActionApplicationConnect),
|
||||
}).WithAgent().Do()
|
||||
chat := createBoundChat(ctx, t, memberClient, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
// An SSH grant passes authorization and reaches the agent check.
|
||||
_, err := memberClient.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusConflict)
|
||||
require.Contains(t, sdkErr.Message, "Agent status")
|
||||
|
||||
owner, err := client.User(ctx, codersdk.Me)
|
||||
require.NoError(t, err)
|
||||
err = db.UpdateWorkspaceACLByID(dbauthz.As(ctx, coderdtest.AuthzUserSubject(owner)), database.UpdateWorkspaceACLByIDParams{
|
||||
ID: workspaceBuild.Workspace.ID,
|
||||
UserACL: aclWith(policy.ActionRead, policy.ActionApplicationConnect),
|
||||
GroupACL: database.WorkspaceACL{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = memberClient.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr = requireSDKError(t, err, http.StatusForbidden)
|
||||
require.Equal(t, "Chat workspace not found.", sdkErr.Message)
|
||||
})
|
||||
|
||||
t.Run("AppConnectOnlyToken", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
OwnerID: firstUser.UserID,
|
||||
}).WithAgent().Do()
|
||||
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
|
||||
|
||||
// chat:* cannot be requested through the token API, so insert
|
||||
// the scoped key directly.
|
||||
_, token := dbgen.APIKey(t, db, database.APIKey{
|
||||
UserID: firstUser.UserID,
|
||||
Scopes: database.APIKeyScopes{
|
||||
database.ApiKeyScopeChat,
|
||||
database.ApiKeyScopeWorkspaceRead,
|
||||
database.ApiKeyScopeWorkspaceApplicationConnect,
|
||||
},
|
||||
})
|
||||
scopedClient := codersdk.NewExperimentalClient(codersdk.New(client.URL, codersdk.WithSessionToken(token)))
|
||||
|
||||
_, err := scopedClient.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusForbidden)
|
||||
require.Equal(t, "Chat workspace not found.", sdkErr.Message)
|
||||
})
|
||||
|
||||
t.Run("Archived", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, api := newChatClientWithAPI(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, client.Client)
|
||||
_ = createChatModel(t, client)
|
||||
|
||||
chat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "archived"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Archiving requires the chat generation to settle first.
|
||||
coderdtest.WaitForChatSettled(ctx, t, api, chat.ID)
|
||||
archived := true
|
||||
err = client.UpdateChat(ctx, chat.ID, codersdk.UpdateChatRequest{
|
||||
Archived: &archived,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
|
||||
require.Contains(t, sdkErr.Message, "archived")
|
||||
})
|
||||
|
||||
t.Run("NotOwner", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
adminClient, _ := newChatClientWithDatabase(t)
|
||||
firstUser := coderdtest.CreateFirstUser(t, adminClient.Client)
|
||||
_ = createChatModel(t, adminClient)
|
||||
|
||||
// The chat is created by the first (owner) user. The second
|
||||
// user has org-admin so they pass RBAC for ActionUpdate, but
|
||||
// the owner-only check should still reject them.
|
||||
secondClientRaw, _ := coderdtest.CreateAnotherUser(t, adminClient.Client, firstUser.OrganizationID,
|
||||
rbac.ScopedRoleOrgAdmin(firstUser.OrganizationID))
|
||||
secondClient := codersdk.NewExperimentalClient(secondClientRaw)
|
||||
|
||||
chat, err := adminClient.CreateChat(ctx, codersdk.CreateChatRequest{
|
||||
OrganizationID: firstUser.OrganizationID,
|
||||
Content: []codersdk.ChatInputPart{
|
||||
{Type: codersdk.ChatInputPartTypeText, Text: "not owner"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = secondClient.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
|
||||
requireSDKError(t, err, http.StatusForbidden)
|
||||
})
|
||||
}
|
||||
@@ -11,3 +11,6 @@ var ChatStartWorkspace = (*API).chatStartWorkspace
|
||||
|
||||
// ChatStopWorkspace exposes chatStopWorkspace for external tests.
|
||||
var ChatStopWorkspace = (*API).chatStopWorkspace
|
||||
|
||||
// NormalizeWorkspaceFileReference exposes normalizeWorkspaceFileReference for tests.
|
||||
var NormalizeWorkspaceFileReference = normalizeWorkspaceFileReference
|
||||
@@ -5940,8 +5940,10 @@ func TestWorkspaceSharingDisabled(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("NoAccessWhenDisabled", func(t *testing.T) {
|
||||
prevWorkspaceACLDisabled := rbac.WorkspaceACLDisabled()
|
||||
t.Cleanup(func() {
|
||||
rbac.ReloadBuiltinRoles(nil)
|
||||
rbac.SetWorkspaceACLDisabled(prevWorkspaceACLDisabled)
|
||||
})
|
||||
|
||||
var (
|
||||
|
||||
@@ -24,6 +24,9 @@ const (
|
||||
// ActivityBumpReasonAppActivity indicates the bump was triggered
|
||||
// by app or port-forward activity.
|
||||
ActivityBumpReasonAppActivity ActivityBumpReason = "app_activity"
|
||||
// ActivityBumpReasonChatWorkspaceUpload indicates the bump was
|
||||
// triggered by a chat file upload streaming into the workspace.
|
||||
ActivityBumpReasonChatWorkspaceUpload ActivityBumpReason = "chat_workspace_upload"
|
||||
)
|
||||
|
||||
// ActivityBumpWorkspace automatically bumps the workspace's auto-off timer
|
||||
|
||||
@@ -51,6 +51,8 @@ File links are metadata, but they are written inside transitions: if a transitio
|
||||
|
||||
Eviction means that a persisted message may reference a file that no longer exists. That's expected: the UI shows the attachment as expired, and when the history is sent to the model, an evicted user upload is replaced with a short placeholder saying the content has expired, while evicted assistant and tool files are dropped. Editing a message that still references an evicted file is refused until the attachment is removed from the edit.
|
||||
|
||||
TODO (#27079): messages can now carry a `workspace-file-reference` part (path, name, size, media type, workspace ID) for files uploaded into the chat's workspace. It is metadata only: no file link is written, coderd validates that the path is scoped to the chat's upload directory and that the workspace ID matches the chat's current binding, and prompt conversion renders the reference as text (`[workspace file: <name> (<size>) at <path>]`) so the bytes never reach the model. Describe this here.
|
||||
|
||||
If the distinction isn't completely clear to you at this point, don't worry. It should become clearer as you learn more about the core state machine.
|
||||
|
||||
## Execution states
|
||||
@@ -592,6 +594,10 @@ This endpoint uses `ClearContext`:
|
||||
|
||||
No other input states are supported: generating chats and chats with queued messages get a conflict error, and archived chats are rejected. Unlike `/compact`, there is no worker round-trip and no model call: the endpoint builds the boundary triplet itself and commits it synchronously inside the API transaction. The transcript is preserved; only future prompts stop seeing pre-clear history. Clearing from an error state clears `last_error`, so a context-overflowed chat gets an instant recovery path that discards the oversized history instead of summarizing it. The prompt-assembly query needs no changes because the clear boundary reuses the compressed model-only anchor shape produced by compaction. Boundary detection (`latestContextBoundaryIndex`) recognizes both `chat_summarized` and `chat_cleared` boundaries, so clear and compaction never reach across each other's boundary. If no active model-visible non-system message follows the latest boundary, the transaction rolls back with a "nothing to clear" conflict, so an empty or already-cleared chat never gains a duplicate boundary. The endpoint is owner-only for symmetry with `/compact`. The web UI surfaces it as the `/clear` slash command.
|
||||
|
||||
### `POST /api/v2/chats/{chat}/workspace-files`
|
||||
|
||||
TODO (#27079): this owner-only endpoint uses no transition. It streams the raw request body to the chat's workspace agent (`/api/v0/upload-chat-file`), preferring the bound agent and otherwise falling back to `agentselect.FindChatAgent` without persisting a binding, and returns the final path so the client can attach a `workspace-file-reference` part to its next message. Describe this here.
|
||||
|
||||
## Pubsub
|
||||
|
||||
The chat worker and the stream loop need real-time notifications when the chat state changes to ensure they are responsive. To achieve this, we use pubsub.
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"charm.land/fantasy"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/google/uuid"
|
||||
"github.com/sqlc-dev/pqtype"
|
||||
"golang.org/x/xerrors"
|
||||
@@ -120,6 +121,7 @@ func ConvertMessagesWithFiles(
|
||||
resolver FileResolver,
|
||||
logger slog.Logger,
|
||||
acceptsFilePart func(mediaType string) bool,
|
||||
chatWorkspaceID uuid.NullUUID,
|
||||
) ([]fantasy.Message, error) {
|
||||
// Phase 1: Parse all messages via ParseContent (→ SDK parts)
|
||||
// and collect file_id references from user messages for batch
|
||||
@@ -202,6 +204,7 @@ func ConvertMessagesWithFiles(
|
||||
resolved,
|
||||
userMissingFilePolicy,
|
||||
acceptsFilePart,
|
||||
chatWorkspaceID,
|
||||
)
|
||||
if len(userParts) == 0 {
|
||||
continue
|
||||
@@ -212,7 +215,7 @@ func ConvertMessagesWithFiles(
|
||||
})
|
||||
case codersdk.ChatMessageRoleAssistant:
|
||||
fantasyParts := normalizeAssistantToolCallInputs(
|
||||
partsToMessageParts(ctx, logger, pm.parts, nil, dropMissingFiles, nil),
|
||||
partsToMessageParts(ctx, logger, pm.parts, nil, dropMissingFiles, nil, chatWorkspaceID),
|
||||
)
|
||||
for _, toolCall := range ExtractToolCalls(fantasyParts) {
|
||||
if toolCall.ToolCallID == "" || strings.TrimSpace(toolCall.ToolName) == "" {
|
||||
@@ -236,7 +239,7 @@ func ConvertMessagesWithFiles(
|
||||
}
|
||||
}
|
||||
}
|
||||
toolParts := partsToMessageParts(ctx, logger, pm.parts, nil, dropMissingFiles, nil)
|
||||
toolParts := partsToMessageParts(ctx, logger, pm.parts, nil, dropMissingFiles, nil, chatWorkspaceID)
|
||||
if len(toolParts) == 0 {
|
||||
continue
|
||||
}
|
||||
@@ -1292,6 +1295,32 @@ func fileReferencePartToText(part codersdk.ChatMessagePart) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// workspaceFilePartToText formats a workspace-file-reference SDK
|
||||
// part as plain text for LLM consumption. The uploaded bytes stay on
|
||||
// the workspace filesystem; only the metadata reference reaches the
|
||||
// model, which can read the file with its workspace tools.
|
||||
//
|
||||
// References carry the workspace they were uploaded to. When the chat
|
||||
// has since been rebound (or unbound), the path no longer exists for
|
||||
// the current agent, so the reference renders as unavailable instead
|
||||
// of steering the model toward a dead path.
|
||||
func workspaceFilePartToText(part codersdk.ChatMessagePart, chatWorkspaceID uuid.NullUUID) string {
|
||||
var sb strings.Builder
|
||||
_, _ = sb.WriteString("[workspace file: ")
|
||||
_, _ = sb.WriteString(part.WorkspaceFileName)
|
||||
if part.WorkspaceFileSize > 0 {
|
||||
_, _ = fmt.Fprintf(&sb, " (%s)", humanize.IBytes(uint64(part.WorkspaceFileSize)))
|
||||
}
|
||||
if !chatWorkspaceID.Valid || part.WorkspaceFileWorkspaceID != chatWorkspaceID.UUID {
|
||||
_, _ = sb.WriteString(", uploaded to a previously attached workspace and no longer accessible]")
|
||||
return sb.String()
|
||||
}
|
||||
_, _ = sb.WriteString(" at ")
|
||||
_, _ = sb.WriteString(part.WorkspaceFilePath)
|
||||
_, _ = sb.WriteString("]")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// toolResultPartToMessagePart converts an SDK tool-result part
|
||||
// into a fantasy ToolResultPart for LLM dispatch.
|
||||
func toolResultPartToMessagePart(logger slog.Logger, part codersdk.ChatMessagePart) fantasy.ToolResultPart {
|
||||
@@ -1432,6 +1461,7 @@ func partsToMessageParts(
|
||||
resolved map[uuid.UUID]FileData,
|
||||
policy missingFilePolicy,
|
||||
acceptsFilePart func(mediaType string) bool,
|
||||
chatWorkspaceID uuid.NullUUID,
|
||||
) []fantasy.MessagePart {
|
||||
result := make([]fantasy.MessagePart, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
@@ -1548,6 +1578,10 @@ func partsToMessageParts(
|
||||
result = append(result, fantasy.TextPart{
|
||||
Text: fileReferencePartToText(part),
|
||||
})
|
||||
case codersdk.ChatMessagePartTypeWorkspaceFileReference:
|
||||
result = append(result, fantasy.TextPart{
|
||||
Text: workspaceFilePartToText(part, chatWorkspaceID),
|
||||
})
|
||||
case codersdk.ChatMessagePartTypeContextFile:
|
||||
if part.ContextFileContent == "" {
|
||||
continue
|
||||
@@ -1876,6 +1910,9 @@ var partNulFields = []partNulField{
|
||||
{name: "ContextFileSkillMetaFile", policy: nulReject, str: func(p *codersdk.ChatMessagePart) *string { return &p.ContextFileSkillMetaFile }},
|
||||
{name: "SkillName", policy: nulReject, str: func(p *codersdk.ChatMessagePart) *string { return &p.SkillName }},
|
||||
{name: "SkillDir", policy: nulReject, str: func(p *codersdk.ChatMessagePart) *string { return &p.SkillDir }},
|
||||
{name: "WorkspaceFilePath", policy: nulReject, str: func(p *codersdk.ChatMessagePart) *string { return &p.WorkspaceFilePath }},
|
||||
{name: "WorkspaceFileName", policy: nulReject, str: func(p *codersdk.ChatMessagePart) *string { return &p.WorkspaceFileName }},
|
||||
{name: "WorkspaceFileMediaType", policy: nulReject, str: func(p *codersdk.ChatMessagePart) *string { return &p.WorkspaceFileMediaType }},
|
||||
}
|
||||
|
||||
// encode applies the reversible NUL encoding to a nulEncode field.
|
||||
|
||||
@@ -64,7 +64,7 @@ func TestConvertMessagesWithFilesPreservesEmptyRedactedReasoning(t *testing.T) {
|
||||
Content: content,
|
||||
ContentVersion: chatprompt.CurrentContentVersion,
|
||||
},
|
||||
}, nil, slogtest.Make(t, nil), nil)
|
||||
}, nil, slogtest.Make(t, nil), nil, uuid.NullUUID{})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
require.Len(t, prompt[0].Content, 2)
|
||||
@@ -147,7 +147,7 @@ func TestConvertMessagesWithFilesRoundTripsAnthropicInterleavedWebSearch(t *test
|
||||
Content: storedContent,
|
||||
ContentVersion: chatprompt.CurrentContentVersion,
|
||||
},
|
||||
}, nil, slogtest.Make(t, nil), nil)
|
||||
}, nil, slogtest.Make(t, nil), nil, uuid.NullUUID{})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
require.Len(t, prompt[0].Content, 5)
|
||||
@@ -200,6 +200,7 @@ func convertMessagesWithoutFiles(t *testing.T, messages []database.ChatMessage)
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return prompt
|
||||
@@ -340,6 +341,7 @@ func TestConvertMessagesWithFiles_ResolvesFileData(t *testing.T) {
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -399,6 +401,7 @@ func TestConvertMessagesWithFiles_MissingFileBackedAttachmentBecomesTextPart(t *
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -447,6 +450,7 @@ func TestConvertMessagesWithFiles_ResolvedZeroByteFileIsDropped(t *testing.T) {
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, prompt)
|
||||
@@ -500,6 +504,7 @@ func TestConvertMessagesWithFiles_MixedResolvedAndMissingFilePartsInSingleMessag
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -567,6 +572,7 @@ func TestConvertMessagesWithFiles_BackwardCompat(t *testing.T) {
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -1531,6 +1537,7 @@ func TestProviderMetadataRoundTrip(t *testing.T) {
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -1580,6 +1587,7 @@ func TestFileReferencePreservation(t *testing.T) {
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -1636,6 +1644,7 @@ func TestAssistantWriteRoundTrip(t *testing.T) {
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -1781,6 +1790,7 @@ func TestMixedFormatConversation(t *testing.T) {
|
||||
prompt, err := chatprompt.ConvertMessagesWithFiles(
|
||||
context.Background(), messages, resolver, slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 6, "all 6 messages should produce prompt entries")
|
||||
@@ -1902,6 +1912,7 @@ func TestQueuedMessageRoundTrip(t *testing.T) {
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -2205,6 +2216,7 @@ func TestNulEscapeRoundTrip(t *testing.T) {
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -2309,6 +2321,7 @@ func TestConvertMessagesWithFiles_FiltersEmptyTextAndReasoningParts(t *testing.T
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -2356,6 +2369,7 @@ func TestConvertMessagesWithFiles_FiltersEmptyTextAndReasoningParts(t *testing.T
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
// 2 messages: assistant + synthetic tool result injected
|
||||
@@ -2391,6 +2405,7 @@ func TestConvertMessagesWithFiles_FiltersEmptyTextAndReasoningParts(t *testing.T
|
||||
nil,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, prompt, "all-empty message should be dropped entirely")
|
||||
@@ -2571,6 +2586,7 @@ func TestConvertMessagesWithFiles_AssistantAttachmentIsNotReplayed(t *testing.T)
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resolverCalls, 1)
|
||||
@@ -2625,6 +2641,7 @@ func convertSingleResolvedFileMessage(t *testing.T, fileID uuid.UUID, fileData c
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return prompt
|
||||
@@ -2715,6 +2732,7 @@ func TestMediaToolResultRoundTrip(t *testing.T) {
|
||||
prompt, convErr := chatprompt.ConvertMessagesWithFiles(
|
||||
ctx, dbMsgs, nil, slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, convErr)
|
||||
return prompt
|
||||
|
||||
@@ -110,3 +110,7 @@ func MarshalToolResult(toolCallID, toolName string, result json.RawMessage, isEr
|
||||
}
|
||||
return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil
|
||||
}
|
||||
|
||||
// WorkspaceFilePartToTextForTest exposes workspaceFilePartToText for
|
||||
// external tests.
|
||||
var WorkspaceFilePartToTextForTest = workspaceFilePartToText
|
||||
@@ -134,6 +134,7 @@ func TestConvertMessagesWithFiles_InlinesTextFilePartWhenProviderRejects(t *test
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
tc.accepts,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -165,6 +166,7 @@ func TestConvertMessagesWithFiles_NilPredicateKeepsFilePart(t *testing.T) {
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
nil,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
@@ -189,6 +191,7 @@ func TestConvertMessagesWithFiles_InlinedTextNotTruncated(t *testing.T) {
|
||||
resolver,
|
||||
slogtest.Make(t, nil),
|
||||
acceptNone,
|
||||
uuid.NullUUID{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, prompt, 1)
|
||||
|
||||
@@ -230,7 +230,9 @@ func chatMessagePartNULSafeType(typ reflect.Type) bool {
|
||||
switch typ {
|
||||
case reflect.TypeFor[bool](),
|
||||
reflect.TypeFor[int](),
|
||||
reflect.TypeFor[int64](),
|
||||
reflect.TypeFor[[]byte](),
|
||||
reflect.TypeFor[uuid.UUID](),
|
||||
reflect.TypeFor[uuid.NullUUID](),
|
||||
reflect.TypeFor[*time.Time]():
|
||||
return true
|
||||
@@ -262,8 +264,12 @@ func chatMessagePartNULProbeValue(t *testing.T, typ reflect.Type) reflect.Value
|
||||
return reflect.ValueOf(true)
|
||||
case reflect.TypeFor[int]():
|
||||
return reflect.ValueOf(42)
|
||||
case reflect.TypeFor[int64]():
|
||||
return reflect.ValueOf(int64(42))
|
||||
case reflect.TypeFor[[]byte]():
|
||||
return reflect.ValueOf([]byte{0, 1, 2})
|
||||
case reflect.TypeFor[uuid.UUID]():
|
||||
return reflect.ValueOf(uuid.MustParse("00000000-0000-0000-0000-000000000002"))
|
||||
case reflect.TypeFor[uuid.NullUUID]():
|
||||
return reflect.ValueOf(uuid.NullUUID{UUID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), Valid: true})
|
||||
case reflect.TypeFor[*time.Time]():
|
||||
|
||||
@@ -29,11 +29,11 @@ func TitlePasteText(data []byte) string {
|
||||
return string(data[:min(len(data), TitlePasteBytePrefix)])
|
||||
}
|
||||
|
||||
// TitleText derives title-generation input from message parts. Text
|
||||
// and file-reference parts are joined in part order. When they yield
|
||||
// nothing, the content of synthetic pasted-text attachments is used
|
||||
// instead, looked up in pasteText by file ID and truncated to
|
||||
// syntheticPasteTitleBudget runes per file.
|
||||
// TitleText derives title-generation input from message parts. Text,
|
||||
// file-reference, and workspace-file-reference parts are joined in
|
||||
// part order. When they yield nothing, the content of synthetic
|
||||
// pasted-text attachments is used instead, looked up in pasteText by
|
||||
// file ID and truncated to syntheticPasteTitleBudget runes per file.
|
||||
//
|
||||
// The chat-creation fallback title and both title-generation paths
|
||||
// must derive their input through this function: auto-titling only
|
||||
@@ -51,6 +51,14 @@ func TitleText(parts []codersdk.ChatMessagePart, pasteText map[uuid.UUID]string)
|
||||
texts = append(texts, text)
|
||||
case codersdk.ChatMessagePartTypeFileReference:
|
||||
texts = append(texts, fileReferencePartToText(part))
|
||||
case codersdk.ChatMessagePartTypeWorkspaceFileReference:
|
||||
// The file name alone: this text can become the visible
|
||||
// fallback title, so it must not carry prompt markers.
|
||||
name := strings.TrimSpace(part.WorkspaceFileName)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
texts = append(texts, name)
|
||||
}
|
||||
}
|
||||
if joined := strings.TrimSpace(strings.Join(texts, " ")); joined != "" {
|
||||
|
||||
@@ -58,6 +58,19 @@ func TestTitleText(t *testing.T) {
|
||||
},
|
||||
want: "explain this [file-reference] app.ts:1",
|
||||
},
|
||||
{
|
||||
name: "renders workspace file references as bare file names",
|
||||
parts: []codersdk.ChatMessagePart{
|
||||
codersdk.ChatMessageText("Say DONE."),
|
||||
{
|
||||
Type: codersdk.ChatMessagePartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/chat-id/files/frozen.zip",
|
||||
WorkspaceFileName: " frozen.zip ",
|
||||
},
|
||||
{Type: codersdk.ChatMessagePartTypeWorkspaceFileReference},
|
||||
},
|
||||
want: "Say DONE. frozen.zip",
|
||||
},
|
||||
{
|
||||
name: "falls back to paste content for file only messages",
|
||||
parts: []codersdk.ChatMessagePart{
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package chatprompt_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
var testChatWorkspaceID = uuid.MustParse("11111111-1111-1111-1111-111111111111")
|
||||
|
||||
func TestWorkspaceFilePartToText(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
part codersdk.ChatMessagePart
|
||||
wantSub []string
|
||||
}{
|
||||
{
|
||||
name: "with_size",
|
||||
part: codersdk.ChatMessagePart{
|
||||
Type: codersdk.ChatMessagePartTypeWorkspaceFileReference,
|
||||
WorkspaceFileWorkspaceID: testChatWorkspaceID,
|
||||
WorkspaceFileName: "archive.zip",
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/abcd1234/files/archive.zip",
|
||||
WorkspaceFileSize: 2048,
|
||||
},
|
||||
wantSub: []string{"archive.zip", "/home/coder/.coder/chats/abcd1234/files/archive.zip", "2.0 KiB"},
|
||||
},
|
||||
{
|
||||
name: "no_size_omits_paren",
|
||||
part: codersdk.ChatMessagePart{
|
||||
Type: codersdk.ChatMessagePartTypeWorkspaceFileReference,
|
||||
WorkspaceFileWorkspaceID: testChatWorkspaceID,
|
||||
WorkspaceFileName: "foo.txt",
|
||||
WorkspaceFilePath: "/home/coder/foo.txt",
|
||||
WorkspaceFileSize: 0,
|
||||
},
|
||||
wantSub: []string{"foo.txt", "/home/coder/foo.txt"},
|
||||
},
|
||||
{
|
||||
name: "mib_unit",
|
||||
part: codersdk.ChatMessagePart{
|
||||
Type: codersdk.ChatMessagePartTypeWorkspaceFileReference,
|
||||
WorkspaceFileWorkspaceID: testChatWorkspaceID,
|
||||
WorkspaceFileName: "big.bin",
|
||||
WorkspaceFilePath: "/home/coder/big.bin",
|
||||
WorkspaceFileSize: 5 * 1024 * 1024,
|
||||
},
|
||||
wantSub: []string{"big.bin", "5.0 MiB"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := chatprompt.WorkspaceFilePartToTextForTest(tt.part, uuid.NullUUID{UUID: testChatWorkspaceID, Valid: true})
|
||||
require.True(t, strings.HasPrefix(got, "[workspace file: "), "expected prefix, got %q", got)
|
||||
require.True(t, strings.HasSuffix(got, "]"), "expected closing bracket, got %q", got)
|
||||
for _, sub := range tt.wantSub {
|
||||
require.Contains(t, got, sub)
|
||||
}
|
||||
if tt.part.WorkspaceFileSize == 0 {
|
||||
require.NotContains(t, got, "(")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceFilePartToTextStaleWorkspace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
part := codersdk.ChatMessagePart{
|
||||
Type: codersdk.ChatMessagePartTypeWorkspaceFileReference,
|
||||
WorkspaceFileWorkspaceID: testChatWorkspaceID,
|
||||
WorkspaceFileName: "archive.zip",
|
||||
WorkspaceFilePath: "/home/coder/.coder/chats/abcd1234/files/archive.zip",
|
||||
WorkspaceFileSize: 2048,
|
||||
}
|
||||
|
||||
t.Run("ReboundWorkspace", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := chatprompt.WorkspaceFilePartToTextForTest(part, uuid.NullUUID{UUID: uuid.MustParse("22222222-2222-2222-2222-222222222222"), Valid: true})
|
||||
require.Contains(t, got, "archive.zip")
|
||||
require.Contains(t, got, "2.0 KiB")
|
||||
require.Contains(t, got, "no longer accessible")
|
||||
require.NotContains(t, got, "/home/coder/.coder/chats", "stale path must not steer the model")
|
||||
})
|
||||
|
||||
t.Run("UnboundChat", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := chatprompt.WorkspaceFilePartToTextForTest(part, uuid.NullUUID{})
|
||||
require.Contains(t, got, "no longer accessible")
|
||||
require.NotContains(t, got, "/home/coder/.coder/chats")
|
||||
})
|
||||
|
||||
t.Run("MatchingWorkspaceKeepsPath", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := chatprompt.WorkspaceFilePartToTextForTest(part, uuid.NullUUID{UUID: testChatWorkspaceID, Valid: true})
|
||||
require.Contains(t, got, "/home/coder/.coder/chats/abcd1234/files/archive.zip")
|
||||
require.NotContains(t, got, "no longer accessible")
|
||||
})
|
||||
}
|
||||
@@ -400,13 +400,13 @@ func (server *Server) prepareGeneration(
|
||||
// accepts a file part is the one for model.Provider().
|
||||
acceptsFilePart := model.AcceptsFilePartMediaType
|
||||
providerType := string(modelRoute.Provider.Type)
|
||||
prompt, err = chatprompt.ConvertMessagesWithFiles(ctx, promptRows[:pendingRowsStart], server.chatFileResolver(providerType), logger, acceptsFilePart)
|
||||
prompt, err = chatprompt.ConvertMessagesWithFiles(ctx, promptRows[:pendingRowsStart], server.chatFileResolver(providerType), logger, acceptsFilePart, chat.WorkspaceID)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("build chat prompt: %w", err)
|
||||
}
|
||||
prompt = replaceUnsupportedToolMedia(ctx, logger, prompt, model, providerType)
|
||||
if pendingRowsStart < len(promptRows) {
|
||||
pendingPrompt, err = chatprompt.ConvertMessagesWithFiles(ctx, promptRows[pendingRowsStart:], server.chatFileResolver(providerType), logger, acceptsFilePart)
|
||||
pendingPrompt, err = chatprompt.ConvertMessagesWithFiles(ctx, promptRows[pendingRowsStart:], server.chatFileResolver(providerType), logger, acceptsFilePart, chat.WorkspaceID)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("build pending chat prompt tail: %w", err)
|
||||
}
|
||||
|
||||
@@ -1366,11 +1366,11 @@ func TestPendingUserSegmentConversionEquivalence(t *testing.T) {
|
||||
start := pendingUserSegmentStart(rows)
|
||||
require.Equal(t, 6, start)
|
||||
|
||||
full, err := chatprompt.ConvertMessagesWithFiles(context.Background(), rows, nil, logger, nil)
|
||||
full, err := chatprompt.ConvertMessagesWithFiles(context.Background(), rows, nil, logger, nil, uuid.NullUUID{})
|
||||
require.NoError(t, err)
|
||||
head, err := chatprompt.ConvertMessagesWithFiles(context.Background(), rows[:start], nil, logger, nil)
|
||||
head, err := chatprompt.ConvertMessagesWithFiles(context.Background(), rows[:start], nil, logger, nil, uuid.NullUUID{})
|
||||
require.NoError(t, err)
|
||||
tail, err := chatprompt.ConvertMessagesWithFiles(context.Background(), rows[start:], nil, logger, nil)
|
||||
tail, err := chatprompt.ConvertMessagesWithFiles(context.Background(), rows[start:], nil, logger, nil, uuid.NullUUID{})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, full, append(append([]fantasy.Message{}, head...), tail...))
|
||||
|
||||
+97
-12
@@ -308,15 +308,16 @@ const (
|
||||
type ChatMessagePartType string
|
||||
|
||||
const (
|
||||
ChatMessagePartTypeText ChatMessagePartType = "text"
|
||||
ChatMessagePartTypeReasoning ChatMessagePartType = "reasoning"
|
||||
ChatMessagePartTypeToolCall ChatMessagePartType = "tool-call"
|
||||
ChatMessagePartTypeToolResult ChatMessagePartType = "tool-result"
|
||||
ChatMessagePartTypeSource ChatMessagePartType = "source"
|
||||
ChatMessagePartTypeFile ChatMessagePartType = "file"
|
||||
ChatMessagePartTypeFileReference ChatMessagePartType = "file-reference"
|
||||
ChatMessagePartTypeContextFile ChatMessagePartType = "context-file"
|
||||
ChatMessagePartTypeSkill ChatMessagePartType = "skill"
|
||||
ChatMessagePartTypeText ChatMessagePartType = "text"
|
||||
ChatMessagePartTypeReasoning ChatMessagePartType = "reasoning"
|
||||
ChatMessagePartTypeToolCall ChatMessagePartType = "tool-call"
|
||||
ChatMessagePartTypeToolResult ChatMessagePartType = "tool-result"
|
||||
ChatMessagePartTypeSource ChatMessagePartType = "source"
|
||||
ChatMessagePartTypeFile ChatMessagePartType = "file"
|
||||
ChatMessagePartTypeFileReference ChatMessagePartType = "file-reference"
|
||||
ChatMessagePartTypeContextFile ChatMessagePartType = "context-file"
|
||||
ChatMessagePartTypeSkill ChatMessagePartType = "skill"
|
||||
ChatMessagePartTypeWorkspaceFileReference ChatMessagePartType = "workspace-file-reference"
|
||||
// ChatMessagePartTypeHookContext is model context injected into a user
|
||||
// prompt by a lifecycle hook. It is included in model prompt assembly
|
||||
// and stripped from every client-facing conversion; the server rejects
|
||||
@@ -340,6 +341,7 @@ func AllChatMessagePartTypes() []ChatMessagePartType {
|
||||
ChatMessagePartTypeFileReference,
|
||||
ChatMessagePartTypeContextFile,
|
||||
ChatMessagePartTypeSkill,
|
||||
ChatMessagePartTypeWorkspaceFileReference,
|
||||
ChatMessagePartTypeHookContext,
|
||||
ChatMessagePartTypeHookNotice,
|
||||
}
|
||||
@@ -465,6 +467,20 @@ type ChatMessagePart struct {
|
||||
// read_skill tool uses the correct filename even when the
|
||||
// agent configured a non-default value.
|
||||
ContextFileSkillMetaFile string `json:"context_file_skill_meta_file,omitempty" typescript:"-"`
|
||||
// WorkspaceFilePath is the absolute path of a workspace upload.
|
||||
// The bytes live on the workspace filesystem; only metadata is
|
||||
// persisted on the message.
|
||||
WorkspaceFilePath string `json:"workspace_file_path" variants:"workspace-file-reference"`
|
||||
// WorkspaceFileName is the sanitized basename of a workspace upload.
|
||||
WorkspaceFileName string `json:"workspace_file_name" variants:"workspace-file-reference"`
|
||||
// WorkspaceFileSize is the byte size of a workspace upload.
|
||||
WorkspaceFileSize int64 `json:"workspace_file_size" variants:"workspace-file-reference"`
|
||||
// WorkspaceFileMediaType is the best-effort declared MIME type.
|
||||
WorkspaceFileMediaType string `json:"workspace_file_media_type,omitempty" variants:"workspace-file-reference?"`
|
||||
// WorkspaceFileWorkspaceID identifies the workspace whose
|
||||
// filesystem holds the uploaded bytes. References are only
|
||||
// readable while the chat stays bound to that workspace.
|
||||
WorkspaceFileWorkspaceID uuid.UUID `json:"workspace_file_workspace_id" format:"uuid" variants:"workspace-file-reference"`
|
||||
}
|
||||
|
||||
// StripInternal removes internal-only fields that must not be
|
||||
@@ -543,6 +559,20 @@ func ChatMessageFileReference(fileName string, startLine, endLine int, content s
|
||||
}
|
||||
}
|
||||
|
||||
// ChatMessageWorkspaceFileReference builds a workspace-file-reference
|
||||
// chat message part. The bytes live on the filesystem of workspace
|
||||
// workspaceID at path; only metadata is persisted on the message.
|
||||
func ChatMessageWorkspaceFileReference(workspaceID uuid.UUID, path, name string, size int64, mediaType string) ChatMessagePart {
|
||||
return ChatMessagePart{
|
||||
Type: ChatMessagePartTypeWorkspaceFileReference,
|
||||
WorkspaceFilePath: path,
|
||||
WorkspaceFileName: name,
|
||||
WorkspaceFileSize: size,
|
||||
WorkspaceFileMediaType: mediaType,
|
||||
WorkspaceFileWorkspaceID: workspaceID,
|
||||
}
|
||||
}
|
||||
|
||||
// ChatMessageSource builds a source chat message part.
|
||||
func ChatMessageSource(sourceID, sourceURL, title string) ChatMessagePart {
|
||||
return ChatMessagePart{
|
||||
@@ -557,9 +587,10 @@ func ChatMessageSource(sourceID, sourceURL, title string) ChatMessagePart {
|
||||
type ChatInputPartType string
|
||||
|
||||
const (
|
||||
ChatInputPartTypeText ChatInputPartType = "text"
|
||||
ChatInputPartTypeFile ChatInputPartType = "file"
|
||||
ChatInputPartTypeFileReference ChatInputPartType = "file-reference"
|
||||
ChatInputPartTypeText ChatInputPartType = "text"
|
||||
ChatInputPartTypeFile ChatInputPartType = "file"
|
||||
ChatInputPartTypeFileReference ChatInputPartType = "file-reference"
|
||||
ChatInputPartTypeWorkspaceFileReference ChatInputPartType = "workspace-file-reference"
|
||||
)
|
||||
|
||||
// ChatInputPart is a single user input part for creating a chat.
|
||||
@@ -574,6 +605,16 @@ type ChatInputPart struct {
|
||||
EndLine int `json:"end_line,omitempty"`
|
||||
// The code content from the diff that was commented on.
|
||||
Content string `json:"content,omitempty"`
|
||||
// The following fields are only set when Type is
|
||||
// ChatInputPartTypeWorkspaceFileReference.
|
||||
WorkspaceFilePath string `json:"workspace_file_path,omitempty"`
|
||||
WorkspaceFileName string `json:"workspace_file_name,omitempty"`
|
||||
WorkspaceFileSize int64 `json:"workspace_file_size,omitempty"`
|
||||
WorkspaceFileMediaType string `json:"workspace_file_media_type,omitempty"`
|
||||
// WorkspaceFileWorkspaceID is the workspace the file was uploaded
|
||||
// to, as returned by the upload endpoint. It must match the chat's
|
||||
// currently bound workspace.
|
||||
WorkspaceFileWorkspaceID uuid.UUID `json:"workspace_file_workspace_id,omitempty" format:"uuid"`
|
||||
}
|
||||
|
||||
// SubmitToolResultsRequest is the body for POST /chats/{id}/tool-results.
|
||||
@@ -755,6 +796,22 @@ type ChatFileDownloadURLResponse struct {
|
||||
MimeType string `json:"mime_type"`
|
||||
}
|
||||
|
||||
// UploadChatWorkspaceFileResponse describes a file uploaded to a
|
||||
// chat's workspace filesystem.
|
||||
type UploadChatWorkspaceFileResponse struct {
|
||||
// Path is the absolute path of the file on the workspace.
|
||||
Path string `json:"path"`
|
||||
// Name is the final basename of the uploaded file.
|
||||
Name string `json:"name"`
|
||||
// Size is the number of bytes written to the workspace.
|
||||
Size int64 `json:"size"`
|
||||
// MediaType is the client-declared content type for display.
|
||||
MediaType string `json:"media_type"`
|
||||
// WorkspaceID is the workspace whose filesystem received the
|
||||
// bytes. Message parts referencing this upload must carry it.
|
||||
WorkspaceID uuid.UUID `json:"workspace_id" format:"uuid"`
|
||||
}
|
||||
|
||||
// ChatMessagesResponse contains the messages and queued messages for a chat.
|
||||
type ChatMessagesResponse struct {
|
||||
Messages []ChatMessage `json:"messages"`
|
||||
@@ -3229,6 +3286,34 @@ func (c *Client) ChatFileDownloadURL(ctx context.Context, fileID uuid.UUID) (Cha
|
||||
return resp, ReadBodyAsJSON(res, &resp)
|
||||
}
|
||||
|
||||
// UploadChatWorkspaceFile streams a file to the chat's workspace
|
||||
// filesystem via the workspace agent. There is no server-imposed size
|
||||
// cap; canceling ctx aborts the stream and no partial target file is
|
||||
// left behind (the agent removes the target when the write fails).
|
||||
func (c *Client) UploadChatWorkspaceFile(ctx context.Context, chatID uuid.UUID, contentType, filename string, rd io.Reader) (UploadChatWorkspaceFileResponse, error) {
|
||||
res, err := c.Request(ctx, http.MethodPost, fmt.Sprintf("/api/v2/chats/%s/workspace-files", chatID), rd, func(r *http.Request) {
|
||||
if contentType != "" {
|
||||
r.Header.Set("Content-Type", contentType)
|
||||
} else {
|
||||
// Drop the SDK's default application/json so the server
|
||||
// can sniff-default an undeclared type.
|
||||
r.Header.Del("Content-Type")
|
||||
}
|
||||
if filename != "" {
|
||||
r.Header.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return UploadChatWorkspaceFileResponse{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusCreated {
|
||||
return UploadChatWorkspaceFileResponse{}, ReadBodyAsError(res)
|
||||
}
|
||||
var resp UploadChatWorkspaceFileResponse
|
||||
return resp, ReadBodyAsJSON(res, &resp)
|
||||
}
|
||||
|
||||
// GetChatFile retrieves a previously uploaded chat file by ID.
|
||||
func (c *Client) GetChatFile(ctx context.Context, fileID uuid.UUID) ([]byte, string, error) {
|
||||
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/chats/files/%s", fileID), nil)
|
||||
|
||||
@@ -3,6 +3,9 @@ package codersdk_test
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -15,6 +18,77 @@ import (
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
func TestUploadChatWorkspaceFileContentType(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
chatID := uuid.MustParse("00000000-0000-0000-0000-000000000001")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
wantHeader string
|
||||
}{
|
||||
{name: "provided", contentType: "text/csv", wantHeader: "text/csv"},
|
||||
{name: "empty", contentType: "", wantHeader: ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, "/api/v2/chats/"+chatID.String()+"/workspace-files", r.URL.Path)
|
||||
require.Equal(t, tt.wantHeader, r.Header.Get("Content-Type"))
|
||||
rw.Header().Set("Content-Type", "application/json")
|
||||
rw.WriteHeader(http.StatusCreated)
|
||||
require.NoError(t, json.NewEncoder(rw).Encode(codersdk.UploadChatWorkspaceFileResponse{
|
||||
Path: "/home/coder/.coder/chats/test/files/data.csv",
|
||||
Name: "data.csv",
|
||||
Size: 4,
|
||||
MediaType: tt.contentType,
|
||||
}))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
serverURL, err := url.Parse(srv.URL)
|
||||
require.NoError(t, err)
|
||||
|
||||
client := codersdk.New(serverURL)
|
||||
_, err = client.UploadChatWorkspaceFile(context.Background(), chatID, tt.contentType, "data.csv", strings.NewReader("data"))
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatMessageWorkspaceFileReference_JSONRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
workspaceID := uuid.MustParse("d8317985-0000-0000-0000-000000000002")
|
||||
part := codersdk.ChatMessageWorkspaceFileReference(
|
||||
workspaceID,
|
||||
"/home/coder/.coder/chats/00000000-0000-0000-0000-000000000001/files/notes.txt",
|
||||
"notes.txt",
|
||||
42,
|
||||
"text/plain",
|
||||
)
|
||||
|
||||
data, err := json.Marshal(part)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(data), `"type":"workspace-file-reference"`)
|
||||
require.Contains(t, string(data), `"workspace_file_path"`)
|
||||
require.Contains(t, string(data), `"workspace_file_name"`)
|
||||
require.Contains(t, string(data), `"workspace_file_size":42`)
|
||||
require.Contains(t, string(data), `"workspace_file_media_type":"text/plain"`)
|
||||
require.Contains(t, string(data), `"workspace_file_workspace_id":"`+workspaceID.String()+`"`)
|
||||
var raw map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(data, &raw))
|
||||
require.NotContains(t, raw, "size")
|
||||
|
||||
var decoded codersdk.ChatMessagePart
|
||||
require.NoError(t, json.Unmarshal(data, &decoded))
|
||||
require.Equal(t, part, decoded)
|
||||
}
|
||||
|
||||
func TestChatModelProviderOptions_MarshalJSON_UsesPlainProviderPayload(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -324,6 +324,7 @@ Querying both counts sessions twice.
|
||||
| `coderd_authz_prepare_authorize_duration_seconds` | histogram | Duration of the 'PrepareAuthorize' call in seconds. | |
|
||||
| `coderd_build_info` | gauge | Describes the current build/version of the Coder server. Value is always 1. | `revision` `version` |
|
||||
| `coderd_chat_auto_archive_records_archived_total` | counter | Total number of chats archived by the auto-archive job (counting both roots and cascaded children). | |
|
||||
| `coderd_chat_workspace_upload_total` | counter | Total chat workspace file uploads by HTTP response status. | `status` |
|
||||
| `coderd_chatd_agents_active` | gauge | Deployment-wide number of chats holding a concurrent-agent capacity slot. Every replica reports the same database-derived value; aggregate with max, not sum. | `pool` |
|
||||
| `coderd_chatd_agents_queued_for_capacity` | gauge | Deployment-wide number of chats waiting for a concurrent-agent capacity slot. Every replica reports the same database-derived value; aggregate with max, not sum. | `pool` |
|
||||
| `coderd_chatd_chats` | gauge | Number of chats being processed, by state. | `state` |
|
||||
|
||||
Generated
+147
-19
@@ -332,7 +332,12 @@ curl -X POST http://coder-server:8080/api/v2/chats \
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"inline_mcp_servers": [
|
||||
@@ -2548,7 +2553,12 @@ curl -X GET http://coder-server:8080/api/v2/chats/{chat}/messages \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -2624,7 +2634,12 @@ curl -X GET http://coder-server:8080/api/v2/chats/{chat}/messages \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -2670,7 +2685,12 @@ curl -X POST http://coder-server:8080/api/v2/chats/{chat}/messages \
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"inline_mcp_servers": [
|
||||
@@ -2768,7 +2788,12 @@ curl -X POST http://coder-server:8080/api/v2/chats/{chat}/messages \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -2843,7 +2868,12 @@ curl -X POST http://coder-server:8080/api/v2/chats/{chat}/messages \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -2919,7 +2949,12 @@ curl -X POST http://coder-server:8080/api/v2/chats/{chat}/messages \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -2966,7 +3001,12 @@ curl -X PATCH http://coder-server:8080/api/v2/chats/{chat}/messages/{message} \
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"mcp_server_ids": [
|
||||
@@ -3049,7 +3089,12 @@ curl -X PATCH http://coder-server:8080/api/v2/chats/{chat}/messages/{message} \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -3124,7 +3169,12 @@ curl -X PATCH http://coder-server:8080/api/v2/chats/{chat}/messages/{message} \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -3650,7 +3700,12 @@ curl -X GET http://coder-server:8080/api/v2/chats/{chat}/stream \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -3724,7 +3779,12 @@ curl -X GET http://coder-server:8080/api/v2/chats/{chat}/stream \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
},
|
||||
"role": "system",
|
||||
"seq": 0
|
||||
@@ -3785,7 +3845,12 @@ curl -X GET http://coder-server:8080/api/v2/chats/{chat}/stream \
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -3879,6 +3944,11 @@ Status Code **200**
|
||||
| `»»» tool_name` | string | false | | |
|
||||
| `»»» type` | [codersdk.ChatMessagePartType](schemas.md#codersdkchatmessageparttype) | false | | |
|
||||
| `»»» url` | string | false | | |
|
||||
| `»»» workspace_file_media_type` | string | false | | Workspace file media type is the best-effort declared MIME type. |
|
||||
| `»»» workspace_file_name` | string | false | | Workspace file name is the sanitized basename of a workspace upload. |
|
||||
| `»»» workspace_file_path` | string | false | | Workspace file path is the absolute path of a workspace upload. The bytes live on the workspace filesystem; only metadata is persisted on the message. |
|
||||
| `»»» workspace_file_size` | integer | false | | Workspace file size is the byte size of a workspace upload. |
|
||||
| `»»» workspace_file_workspace_id` | string(uuid) | false | | Workspace file workspace ID identifies the workspace whose filesystem holds the uploaded bytes. References are only readable while the chat stays bound to that workspace. |
|
||||
| `»» created_at` | string(date-time) | false | | |
|
||||
| `»» created_by` | string(uuid) | false | | |
|
||||
| `»» id` | integer | false | | |
|
||||
@@ -3919,12 +3989,12 @@ Status Code **200**
|
||||
|
||||
#### Enumerated Values
|
||||
|
||||
| Property | Value(s) |
|
||||
|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `kind` | `auth`, `config`, `content_filter`, `generic`, `hook_denied`, `hook_dispatch_failed`, `missing_key`, `overloaded`, `provider_disabled`, `rate_limit`, `stream_silence_timeout`, `timeout`, `usage_limit` |
|
||||
| `type` | `action_required`, `context-file`, `error`, `file`, `file-reference`, `history_reset`, `hook-context`, `hook-notice`, `message`, `message_part`, `preview_reset`, `queue_update`, `reasoning`, `retry`, `skill`, `source`, `status`, `text`, `tool-call`, `tool-result` |
|
||||
| `role` | `assistant`, `system`, `tool`, `user` |
|
||||
| `status` | `error`, `interrupting`, `requires_action`, `running`, `waiting` |
|
||||
| Property | Value(s) |
|
||||
|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `kind` | `auth`, `config`, `content_filter`, `generic`, `hook_denied`, `hook_dispatch_failed`, `missing_key`, `overloaded`, `provider_disabled`, `rate_limit`, `stream_silence_timeout`, `timeout`, `usage_limit` |
|
||||
| `type` | `action_required`, `context-file`, `error`, `file`, `file-reference`, `history_reset`, `hook-context`, `hook-notice`, `message`, `message_part`, `preview_reset`, `queue_update`, `reasoning`, `retry`, `skill`, `source`, `status`, `text`, `tool-call`, `tool-result`, `workspace-file-reference` |
|
||||
| `role` | `assistant`, `system`, `tool`, `user` |
|
||||
| `status` | `error`, `interrupting`, `requires_action`, `running`, `waiting` |
|
||||
|
||||
To perform this operation, you must be authenticated. [Learn more](authentication.md).
|
||||
|
||||
@@ -4057,6 +4127,64 @@ curl -X POST http://coder-server:8080/api/v2/chats/{chat}/tool-results \
|
||||
|
||||
To perform this operation, you must be authenticated. [Learn more](authentication.md).
|
||||
|
||||
## Upload a file to a chat's workspace
|
||||
|
||||
### Code samples
|
||||
|
||||
```sh
|
||||
# Example request using curl
|
||||
curl -X POST http://coder-server:8080/api/v2/chats/{chat}/workspace-files \
|
||||
-H 'Content-Type: */*' \
|
||||
-H 'Accept: application/json' \
|
||||
-H 'Content-Disposition: string' \
|
||||
-H 'Coder-Session-Token: API_KEY' \
|
||||
--data-binary '@archive.zip'
|
||||
```
|
||||
|
||||
`POST /api/v2/chats/{chat}/workspace-files`
|
||||
|
||||
Streams the request body into the chat workspace's
|
||||
upload directory. The request Content-Type header is
|
||||
recorded as the file's media type. There is no
|
||||
server-imposed size cap; client cancellation aborts the
|
||||
stream and the agent leaves no partial target file behind.
|
||||
|
||||
### Parameters
|
||||
|
||||
| Name | In | Type | Required | Description |
|
||||
|-----------------------|--------|--------------|----------|-------------------------------------------------|
|
||||
| `chat` | path | string(uuid) | true | Chat ID |
|
||||
| `Content-Disposition` | header | string | true | Filename of the file (attachment; filename=...) |
|
||||
| `body` | body | string | true | Raw file binary data |
|
||||
|
||||
### Example responses
|
||||
|
||||
> 201 Response
|
||||
|
||||
```json
|
||||
{
|
||||
"media_type": "string",
|
||||
"name": "string",
|
||||
"path": "string",
|
||||
"size": 0,
|
||||
"workspace_id": "0967198e-ec7b-4c6b-b4d3-f71244cadbe9"
|
||||
}
|
||||
```
|
||||
|
||||
### Responses
|
||||
|
||||
| Status | Meaning | Description | Schema |
|
||||
|--------|----------------------------------------------------------------------------|-----------------------|------------------------------------------------------------------------------------------------|
|
||||
| 201 | [Created](https://tools.ietf.org/html/rfc7231#section-6.3.2) | Created | [codersdk.UploadChatWorkspaceFileResponse](schemas.md#codersdkuploadchatworkspacefileresponse) |
|
||||
| 400 | [Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1) | Bad Request | [codersdk.Response](schemas.md#codersdkresponse) |
|
||||
| 403 | [Forbidden](https://tools.ietf.org/html/rfc7231#section-6.5.3) | Forbidden | [codersdk.Response](schemas.md#codersdkresponse) |
|
||||
| 409 | [Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8) | Conflict | [codersdk.Response](schemas.md#codersdkresponse) |
|
||||
| 429 | [Too Many Requests](https://tools.ietf.org/html/rfc6585#section-4) | Too Many Requests | [codersdk.Response](schemas.md#codersdkresponse) |
|
||||
| 500 | [Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1) | Internal Server Error | [codersdk.Response](schemas.md#codersdkresponse) |
|
||||
| 502 | [Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3) | Bad Gateway | [codersdk.Response](schemas.md#codersdkresponse) |
|
||||
|
||||
To perform this operation, you must be authenticated. [Learn more](authentication.md).
|
||||
|
||||
## List AI models and provider descriptors in an organization
|
||||
|
||||
### Code samples
|
||||
|
||||
Generated
+155
-33
@@ -3018,21 +3018,31 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
```
|
||||
|
||||
### Properties
|
||||
|
||||
| Name | Type | Required | Restrictions | Description |
|
||||
|--------------|----------------------------------------------------------|----------|--------------|--------------------------------------------------------------------------------|
|
||||
| `content` | string | false | | The code content from the diff that was commented on. |
|
||||
| `end_line` | integer | false | | |
|
||||
| `file_id` | string | false | | |
|
||||
| `file_name` | string | false | | The following fields are only set when Type is ChatInputPartTypeFileReference. |
|
||||
| `start_line` | integer | false | | |
|
||||
| `text` | string | false | | |
|
||||
| `type` | [codersdk.ChatInputPartType](#codersdkchatinputparttype) | false | | |
|
||||
| Name | Type | Required | Restrictions | Description |
|
||||
|-------------------------------|----------------------------------------------------------|----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `content` | string | false | | The code content from the diff that was commented on. |
|
||||
| `end_line` | integer | false | | |
|
||||
| `file_id` | string | false | | |
|
||||
| `file_name` | string | false | | The following fields are only set when Type is ChatInputPartTypeFileReference. |
|
||||
| `start_line` | integer | false | | |
|
||||
| `text` | string | false | | |
|
||||
| `type` | [codersdk.ChatInputPartType](#codersdkchatinputparttype) | false | | |
|
||||
| `workspace_file_media_type` | string | false | | |
|
||||
| `workspace_file_name` | string | false | | |
|
||||
| `workspace_file_path` | string | false | | The following fields are only set when Type is ChatInputPartTypeWorkspaceFileReference. |
|
||||
| `workspace_file_size` | integer | false | | |
|
||||
| `workspace_file_workspace_id` | string | false | | Workspace file workspace ID is the workspace the file was uploaded to, as returned by the upload endpoint. It must match the chat's currently bound workspace. |
|
||||
|
||||
## codersdk.ChatInputPartType
|
||||
|
||||
@@ -3044,9 +3054,9 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
|
||||
#### Enumerated Values
|
||||
|
||||
| Value(s) |
|
||||
|----------------------------------|
|
||||
| `file`, `file-reference`, `text` |
|
||||
| Value(s) |
|
||||
|--------------------------------------------------------------|
|
||||
| `file`, `file-reference`, `text`, `workspace-file-reference` |
|
||||
|
||||
## codersdk.ChatMessage
|
||||
|
||||
@@ -3106,7 +3116,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -3196,7 +3211,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -3244,6 +3264,11 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
| `tool_name` | string | false | | |
|
||||
| `type` | [codersdk.ChatMessagePartType](#codersdkchatmessageparttype) | false | | |
|
||||
| `url` | string | false | | |
|
||||
| `workspace_file_media_type` | string | false | | Workspace file media type is the best-effort declared MIME type. |
|
||||
| `workspace_file_name` | string | false | | Workspace file name is the sanitized basename of a workspace upload. |
|
||||
| `workspace_file_path` | string | false | | Workspace file path is the absolute path of a workspace upload. The bytes live on the workspace filesystem; only metadata is persisted on the message. |
|
||||
| `workspace_file_size` | integer | false | | Workspace file size is the byte size of a workspace upload. |
|
||||
| `workspace_file_workspace_id` | string | false | | Workspace file workspace ID identifies the workspace whose filesystem holds the uploaded bytes. References are only readable while the chat stays bound to that workspace. |
|
||||
|
||||
## codersdk.ChatMessagePartType
|
||||
|
||||
@@ -3255,9 +3280,9 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
|
||||
#### Enumerated Values
|
||||
|
||||
| Value(s) |
|
||||
|---------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `context-file`, `file`, `file-reference`, `hook-context`, `hook-notice`, `reasoning`, `skill`, `source`, `text`, `tool-call`, `tool-result` |
|
||||
| Value(s) |
|
||||
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `context-file`, `file`, `file-reference`, `hook-context`, `hook-notice`, `reasoning`, `skill`, `source`, `text`, `tool-call`, `tool-result`, `workspace-file-reference` |
|
||||
|
||||
## codersdk.ChatMessageRole
|
||||
|
||||
@@ -3360,7 +3385,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -3436,7 +3466,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -4752,7 +4787,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -4910,7 +4950,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -4984,7 +5029,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
},
|
||||
"role": "system",
|
||||
"seq": 0
|
||||
@@ -5045,7 +5095,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -5155,7 +5210,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
},
|
||||
"role": "system",
|
||||
"seq": 0
|
||||
@@ -5813,7 +5873,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"inline_mcp_servers": [
|
||||
@@ -5920,7 +5985,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -5995,7 +6065,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -6071,7 +6146,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -6289,7 +6369,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"inline_mcp_servers": [
|
||||
@@ -8821,7 +8906,12 @@ CreateWorkspaceRequest provides options for creating a new workspace. Only one o
|
||||
"file_name": "string",
|
||||
"start_line": 0,
|
||||
"text": "string",
|
||||
"type": "text"
|
||||
"type": "text",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"mcp_server_ids": [
|
||||
@@ -8903,7 +8993,12 @@ CreateWorkspaceRequest provides options for creating a new workspace. Only one o
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -8978,7 +9073,12 @@ CreateWorkspaceRequest provides options for creating a new workspace. Only one o
|
||||
"tool_call_id": "string",
|
||||
"tool_name": "string",
|
||||
"type": "text",
|
||||
"url": "string"
|
||||
"url": "string",
|
||||
"workspace_file_media_type": "string",
|
||||
"workspace_file_name": "string",
|
||||
"workspace_file_path": "string",
|
||||
"workspace_file_size": 0,
|
||||
"workspace_file_workspace_id": "74c05446-1c56-4543-82a9-03f2bf73b2ab"
|
||||
}
|
||||
],
|
||||
"created_at": "2019-08-24T14:15:22Z",
|
||||
@@ -16666,6 +16766,28 @@ If the schedule is empty, the user will be updated to use the default schedule.|
|
||||
|------|--------|----------|--------------|-------------|
|
||||
| `id` | string | false | | |
|
||||
|
||||
## codersdk.UploadChatWorkspaceFileResponse
|
||||
|
||||
```json
|
||||
{
|
||||
"media_type": "string",
|
||||
"name": "string",
|
||||
"path": "string",
|
||||
"size": 0,
|
||||
"workspace_id": "0967198e-ec7b-4c6b-b4d3-f71244cadbe9"
|
||||
}
|
||||
```
|
||||
|
||||
### Properties
|
||||
|
||||
| Name | Type | Required | Restrictions | Description |
|
||||
|----------------|---------|----------|--------------|-------------------------------------------------------------------------------------------------------------------------|
|
||||
| `media_type` | string | false | | Media type is the client-declared content type for display. |
|
||||
| `name` | string | false | | Name is the final basename of the uploaded file. |
|
||||
| `path` | string | false | | Path is the absolute path of the file on the workspace. |
|
||||
| `size` | integer | false | | Size is the number of bytes written to the workspace. |
|
||||
| `workspace_id` | string | false | | Workspace ID is the workspace whose filesystem received the bytes. Message parts referencing this upload must carry it. |
|
||||
|
||||
## codersdk.UploadResponse
|
||||
|
||||
```json
|
||||
|
||||
@@ -337,6 +337,9 @@ coderd_build_info{version="",revision=""} 0
|
||||
# HELP coderd_chat_auto_archive_records_archived_total Total number of chats archived by the auto-archive job (counting both roots and cascaded children).
|
||||
# TYPE coderd_chat_auto_archive_records_archived_total counter
|
||||
coderd_chat_auto_archive_records_archived_total 0
|
||||
# HELP coderd_chat_workspace_upload_total Total chat workspace file uploads by HTTP response status.
|
||||
# TYPE coderd_chat_workspace_upload_total counter
|
||||
coderd_chat_workspace_upload_total{status=""} 0
|
||||
# HELP coderd_chatd_agents_active Deployment-wide number of chats holding a concurrent-agent capacity slot. Every replica reports the same database-derived value; aggregate with max, not sum.
|
||||
# TYPE coderd_chatd_agents_active gauge
|
||||
coderd_chatd_agents_active{pool=""} 0
|
||||
|
||||
Generated
+82
-2
@@ -2670,15 +2670,34 @@ export interface ChatInputPart {
|
||||
* The code content from the diff that was commented on.
|
||||
*/
|
||||
readonly content?: string;
|
||||
/**
|
||||
* The following fields are only set when Type is
|
||||
* ChatInputPartTypeWorkspaceFileReference.
|
||||
*/
|
||||
readonly workspace_file_path?: string;
|
||||
readonly workspace_file_name?: string;
|
||||
readonly workspace_file_size?: number;
|
||||
readonly workspace_file_media_type?: string;
|
||||
/**
|
||||
* WorkspaceFileWorkspaceID is the workspace the file was uploaded
|
||||
* to, as returned by the upload endpoint. It must match the chat's
|
||||
* currently bound workspace.
|
||||
*/
|
||||
readonly workspace_file_workspace_id?: string;
|
||||
}
|
||||
|
||||
// From codersdk/chats.go
|
||||
export type ChatInputPartType = "file" | "file-reference" | "text";
|
||||
export type ChatInputPartType =
|
||||
| "file"
|
||||
| "file-reference"
|
||||
| "text"
|
||||
| "workspace-file-reference";
|
||||
|
||||
export const ChatInputPartTypes: ChatInputPartType[] = [
|
||||
"file",
|
||||
"file-reference",
|
||||
"text",
|
||||
"workspace-file-reference",
|
||||
];
|
||||
|
||||
// From codersdk/chats.go
|
||||
@@ -2748,6 +2767,7 @@ export type ChatMessagePart =
|
||||
| ChatFileReferencePart
|
||||
| ChatContextFilePart
|
||||
| ChatSkillPart
|
||||
| ChatWorkspaceFileReferencePart
|
||||
| ChatHookNoticePart;
|
||||
|
||||
// From codersdk/chats.go
|
||||
@@ -2762,7 +2782,8 @@ export type ChatMessagePartType =
|
||||
| "source"
|
||||
| "text"
|
||||
| "tool-call"
|
||||
| "tool-result";
|
||||
| "tool-result"
|
||||
| "workspace-file-reference";
|
||||
|
||||
export const ChatMessagePartTypes: ChatMessagePartType[] = [
|
||||
"context-file",
|
||||
@@ -2776,6 +2797,7 @@ export const ChatMessagePartTypes: ChatMessagePartType[] = [
|
||||
"text",
|
||||
"tool-call",
|
||||
"tool-result",
|
||||
"workspace-file-reference",
|
||||
];
|
||||
|
||||
// From codersdk/chats.go
|
||||
@@ -3657,6 +3679,35 @@ export const ChatWatchEventKinds: ChatWatchEventKind[] = [
|
||||
"title_change",
|
||||
];
|
||||
|
||||
// From codersdk/chats.go
|
||||
export interface ChatWorkspaceFileReferencePart {
|
||||
readonly type: "workspace-file-reference";
|
||||
/**
|
||||
* WorkspaceFilePath is the absolute path of a workspace upload.
|
||||
* The bytes live on the workspace filesystem; only metadata is
|
||||
* persisted on the message.
|
||||
*/
|
||||
readonly workspace_file_path: string;
|
||||
/**
|
||||
* WorkspaceFileName is the sanitized basename of a workspace upload.
|
||||
*/
|
||||
readonly workspace_file_name: string;
|
||||
/**
|
||||
* WorkspaceFileSize is the byte size of a workspace upload.
|
||||
*/
|
||||
readonly workspace_file_size: number;
|
||||
/**
|
||||
* WorkspaceFileWorkspaceID identifies the workspace whose
|
||||
* filesystem holds the uploaded bytes. References are only
|
||||
* readable while the chat stays bound to that workspace.
|
||||
*/
|
||||
readonly workspace_file_workspace_id: string;
|
||||
/**
|
||||
* WorkspaceFileMediaType is the best-effort declared MIME type.
|
||||
*/
|
||||
readonly workspace_file_media_type?: string;
|
||||
}
|
||||
|
||||
// From codersdk/chats.go
|
||||
/**
|
||||
* ChatWorkspaceTTLResponse is the response for getting the chat
|
||||
@@ -10665,6 +10716,35 @@ export interface UploadChatFileResponse {
|
||||
readonly id: string;
|
||||
}
|
||||
|
||||
// From codersdk/chats.go
|
||||
/**
|
||||
* UploadChatWorkspaceFileResponse describes a file uploaded to a
|
||||
* chat's workspace filesystem.
|
||||
*/
|
||||
export interface UploadChatWorkspaceFileResponse {
|
||||
/**
|
||||
* Path is the absolute path of the file on the workspace.
|
||||
*/
|
||||
readonly path: string;
|
||||
/**
|
||||
* Name is the final basename of the uploaded file.
|
||||
*/
|
||||
readonly name: string;
|
||||
/**
|
||||
* Size is the number of bytes written to the workspace.
|
||||
*/
|
||||
readonly size: number;
|
||||
/**
|
||||
* MediaType is the client-declared content type for display.
|
||||
*/
|
||||
readonly media_type: string;
|
||||
/**
|
||||
* WorkspaceID is the workspace whose filesystem received the
|
||||
* bytes. Message parts referencing this upload must carry it.
|
||||
*/
|
||||
readonly workspace_id: string;
|
||||
}
|
||||
|
||||
// From codersdk/files.go
|
||||
/**
|
||||
* UploadResponse contains the hash to reference the uploaded file.
|
||||
|
||||
+25
@@ -2394,3 +2394,28 @@ export const ThinkingBlockWithShellTools: Story = {
|
||||
]),
|
||||
},
|
||||
};
|
||||
|
||||
export const UserMessageWithWorkspaceFileReference: Story = {
|
||||
args: {
|
||||
...defaultArgs,
|
||||
parsedMessages: buildMessages([
|
||||
{
|
||||
...baseMessage,
|
||||
id: 1,
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Unzip this in my workspace" },
|
||||
{
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path:
|
||||
"/home/coder/.coder/chats/story-chat/files/dataset.zip",
|
||||
workspace_file_name: "dataset.zip",
|
||||
workspace_file_size: 4096,
|
||||
workspace_file_media_type: "application/zip",
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
},
|
||||
};
|
||||
@@ -179,6 +179,17 @@ const ChatMessageItem = memo<{
|
||||
isAwaitingFirstStreamChunk,
|
||||
})
|
||||
: undefined;
|
||||
// Editing rebuilds the message from text + attachments and would
|
||||
// drop workspace file references, so such messages are read-only.
|
||||
const canEditUserMessage =
|
||||
isUser &&
|
||||
messageId !== undefined &&
|
||||
Boolean(onEditUserMessage) &&
|
||||
!displayState?.hasWorkspaceFileReferences;
|
||||
const canJumpBetweenUserMessages =
|
||||
isUser &&
|
||||
Boolean(onJumpToUserMessage) &&
|
||||
(prevUserMessageKey !== undefined || nextUserMessageKey !== undefined);
|
||||
if (displayState?.shouldHide) {
|
||||
return null;
|
||||
}
|
||||
@@ -278,7 +289,8 @@ const ChatMessageItem = memo<{
|
||||
{displayState &&
|
||||
!hideActions &&
|
||||
(displayState.hasCopyableContent ||
|
||||
(isUser && onEditUserMessage)) && (
|
||||
canEditUserMessage ||
|
||||
canJumpBetweenUserMessages) && (
|
||||
<div
|
||||
className={cn(
|
||||
"mt-0.5 flex items-center gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/msg:opacity-100",
|
||||
@@ -294,7 +306,7 @@ const ChatMessageItem = memo<{
|
||||
tooltipSide="bottom"
|
||||
/>
|
||||
)}
|
||||
{isUser && messageId !== undefined && onEditUserMessage && (
|
||||
{canEditUserMessage && messageId !== undefined && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
@@ -303,9 +315,16 @@ const ChatMessageItem = memo<{
|
||||
className="size-6"
|
||||
aria-label="Edit message"
|
||||
onClick={() => {
|
||||
const { text, fileBlocks } =
|
||||
const editablePayload =
|
||||
getEditableUserMessagePayload(message);
|
||||
onEditUserMessage(messageId, text, fileBlocks);
|
||||
if (!editablePayload) {
|
||||
return;
|
||||
}
|
||||
onEditUserMessage?.(
|
||||
messageId,
|
||||
editablePayload.text,
|
||||
editablePayload.fileBlocks,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<PencilIcon />
|
||||
|
||||
@@ -410,6 +410,10 @@ export const BlockList: FC<BlockListProps> = ({
|
||||
sources={block.sources}
|
||||
/>
|
||||
);
|
||||
// Workspace file references render through the user
|
||||
// message display state, not as timeline blocks.
|
||||
case "workspace-file-reference":
|
||||
return null;
|
||||
default: {
|
||||
const _exhaustive: never = block;
|
||||
return _exhaustive;
|
||||
|
||||
@@ -57,6 +57,11 @@ const renderUserInlineContent = (blocks: readonly UserInlineRenderBlock[]) => {
|
||||
);
|
||||
};
|
||||
|
||||
const workspaceFilePlaceholderText = (count: number): string =>
|
||||
count === 1
|
||||
? "Workspace file attached. Display support is coming soon."
|
||||
: `${count} workspace files attached. Display support is coming soon.`;
|
||||
|
||||
export const UserMessageContent: FC<{
|
||||
displayState: MessageDisplayState;
|
||||
markdown: string;
|
||||
@@ -109,6 +114,13 @@ export const UserMessageContent: FC<{
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{displayState.hasWorkspaceFileReferences && (
|
||||
<div className="rounded-md border border-border-default bg-surface-tertiary px-2.5 py-1.5 text-xs text-content-secondary">
|
||||
{workspaceFilePlaceholderText(
|
||||
displayState.workspaceFileReferenceCount,
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</MessageContent>
|
||||
</Message>
|
||||
|
||||
@@ -333,6 +333,43 @@ describe("deriveMessageDisplayState", () => {
|
||||
expect(getDisplayState(message).needsAssistantBottomSpacer).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps workspace-file-only user messages visible for the placeholder", () => {
|
||||
const message = buildMessage([
|
||||
{
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path: "/home/coder/.coder/chats/chat-1/files/data.csv",
|
||||
workspace_file_name: "data.csv",
|
||||
workspace_file_size: 42,
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
},
|
||||
]);
|
||||
|
||||
const state = getDisplayState(message);
|
||||
expect(state.shouldHide).toBe(false);
|
||||
expect(state.hasWorkspaceFileReferences).toBe(true);
|
||||
expect(state.workspaceFileReferenceCount).toBe(1);
|
||||
expect(state.hasCopyableContent).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps text with workspace file references visible but not copyable", () => {
|
||||
const message = buildMessage([
|
||||
{ type: "text", text: "Use this file." },
|
||||
{
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path: "/home/coder/.coder/chats/chat-1/files/data.csv",
|
||||
workspace_file_name: "data.csv",
|
||||
workspace_file_size: 42,
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
},
|
||||
]);
|
||||
|
||||
const state = getDisplayState(message);
|
||||
expect(state.shouldHide).toBe(false);
|
||||
expect(state.hasUserMessageBody).toBe(true);
|
||||
expect(state.hasWorkspaceFileReferences).toBe(true);
|
||||
expect(state.hasCopyableContent).toBe(false);
|
||||
});
|
||||
|
||||
it("hides assistant messages with no renderable content", () => {
|
||||
const message = buildMessage([], "assistant");
|
||||
|
||||
|
||||
@@ -12,13 +12,19 @@ export type UserInlineRenderBlock =
|
||||
| Extract<RenderBlock, { type: "file-reference" }>;
|
||||
|
||||
type FileRenderBlock = Extract<RenderBlock, { type: "file" }>;
|
||||
type WorkspaceFileReferenceBlock = Extract<
|
||||
RenderBlock,
|
||||
{ type: "workspace-file-reference" }
|
||||
>;
|
||||
|
||||
export type MessageDisplayState = {
|
||||
shouldHide: boolean;
|
||||
userInlineContent: UserInlineRenderBlock[];
|
||||
userFileBlocks: FileRenderBlock[];
|
||||
workspaceFileReferenceCount: number;
|
||||
hasUserMessageBody: boolean;
|
||||
hasFileBlocks: boolean;
|
||||
hasWorkspaceFileReferences: boolean;
|
||||
hasCopyableContent: boolean;
|
||||
needsAssistantBottomSpacer: boolean;
|
||||
};
|
||||
@@ -41,6 +47,11 @@ const isUserInlineRenderBlock = (
|
||||
const isFileRenderBlock = (block: RenderBlock): block is FileRenderBlock =>
|
||||
block.type === "file";
|
||||
|
||||
const isWorkspaceFileReferenceBlock = (
|
||||
block: RenderBlock,
|
||||
): block is WorkspaceFileReferenceBlock =>
|
||||
block.type === "workspace-file-reference";
|
||||
|
||||
const isProviderToolResultOnlyMessage = (
|
||||
parts: readonly TypesGen.ChatMessagePart[],
|
||||
): boolean =>
|
||||
@@ -63,8 +74,12 @@ const getRenderableContentState = (parsed: ParsedMessageContent) => {
|
||||
}),
|
||||
);
|
||||
const visibleToolIds = new Set(visibleTools.map((tool) => tool.id));
|
||||
// Workspace file references render via the display-state
|
||||
// placeholder, not as standalone timeline blocks.
|
||||
const visibleBlocks = parsed.blocks.filter(
|
||||
(block) => block.type !== "tool" || visibleToolIds.has(block.id),
|
||||
(block) =>
|
||||
block.type !== "workspace-file-reference" &&
|
||||
(block.type !== "tool" || visibleToolIds.has(block.id)),
|
||||
);
|
||||
const hasRenderableContent =
|
||||
visibleBlocks.length > 0 ||
|
||||
@@ -141,6 +156,10 @@ export const deriveMessageDisplayState = ({
|
||||
? parsed.blocks.filter(isUserInlineRenderBlock)
|
||||
: [];
|
||||
const userFileBlocks = isUser ? parsed.blocks.filter(isFileRenderBlock) : [];
|
||||
const workspaceFileReferenceCount = isUser
|
||||
? parsed.blocks.filter(isWorkspaceFileReferenceBlock).length
|
||||
: 0;
|
||||
const hasWorkspaceFileReferences = workspaceFileReferenceCount > 0;
|
||||
const hasFileAttachments = parsed.blocks.some(isFileRenderBlock);
|
||||
const hasUserMessageBody =
|
||||
userInlineContent.length > 0 || Boolean(parsed.markdown.trim());
|
||||
@@ -154,6 +173,7 @@ export const deriveMessageDisplayState = ({
|
||||
const hasCopyableContent =
|
||||
Boolean(parsed.markdown.trim()) &&
|
||||
!hasFileAttachments &&
|
||||
!hasWorkspaceFileReferences &&
|
||||
(isUser || endsWithResponseBlock);
|
||||
const needsAssistantBottomSpacer =
|
||||
!hideActions &&
|
||||
@@ -166,8 +186,10 @@ export const deriveMessageDisplayState = ({
|
||||
shouldHide: shouldHideTimelineEntry({ message, parsed }),
|
||||
userInlineContent,
|
||||
userFileBlocks,
|
||||
workspaceFileReferenceCount,
|
||||
hasUserMessageBody,
|
||||
hasFileBlocks,
|
||||
hasWorkspaceFileReferences,
|
||||
hasCopyableContent,
|
||||
needsAssistantBottomSpacer,
|
||||
};
|
||||
|
||||
@@ -155,6 +155,27 @@ describe("getEditableUserMessagePayload", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("returns undefined for messages with workspace file references", () => {
|
||||
const message: ChatMessage = {
|
||||
id: 1,
|
||||
chat_id: "chat-1",
|
||||
created_at: "2026-04-21T00:00:00.000Z",
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Please use this file." },
|
||||
{
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path: "/home/coder/.coder/chats/chat-1/files/data.csv",
|
||||
workspace_file_name: "data.csv",
|
||||
workspace_file_size: 42,
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(getEditableUserMessagePayload(message)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves whitespace-only text parts when concatenating", () => {
|
||||
// The server-side prompt-history cycle joins text parts
|
||||
// verbatim via `string_agg(part->>'text', '' ORDER BY ordinality)`.
|
||||
@@ -445,6 +466,33 @@ describe("parseMessageContent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("parses workspace file references without changing markdown", () => {
|
||||
const result = parseMessageContent([
|
||||
{ type: "text", text: "Use this file." },
|
||||
{
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path: "/home/coder/.coder/chats/chat-1/files/data.csv",
|
||||
workspace_file_name: "data.csv",
|
||||
workspace_file_size: 42,
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
workspace_file_media_type: "text/csv",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result.markdown).toBe("Use this file.");
|
||||
expect(result.blocks).toEqual([
|
||||
{ type: "response", text: "Use this file." },
|
||||
{
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path: "/home/coder/.coder/chats/chat-1/files/data.csv",
|
||||
workspace_file_name: "data.csv",
|
||||
workspace_file_size: 42,
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
workspace_file_media_type: "text/csv",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips provider_executed tool-call parts", () => {
|
||||
const result = parseMessageContent([
|
||||
{
|
||||
|
||||
@@ -324,6 +324,10 @@ export const parseMessageContent = (
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "workspace-file-reference": {
|
||||
parsed.blocks.push(part);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const _exhaustive: never = part;
|
||||
break;
|
||||
@@ -341,12 +345,29 @@ const isEditableUserMessageFileBlock = (
|
||||
): block is TypesGen.ChatFilePart =>
|
||||
block.type === "file" && isEditableAttachmentMediaType(block.media_type);
|
||||
|
||||
const messageHasWorkspaceFileReferences = (
|
||||
message: TypesGen.ChatMessage,
|
||||
): boolean =>
|
||||
(message.content ?? []).some(
|
||||
(part) => part.type === "workspace-file-reference",
|
||||
);
|
||||
|
||||
export const getEditableUserMessagePayload = (
|
||||
message: TypesGen.ChatMessage,
|
||||
): {
|
||||
text: string;
|
||||
fileBlocks: readonly TypesGen.ChatMessagePart[] | undefined;
|
||||
} => {
|
||||
):
|
||||
| {
|
||||
text: string;
|
||||
fileBlocks: readonly TypesGen.ChatMessagePart[] | undefined;
|
||||
}
|
||||
| undefined => {
|
||||
// Editing rebuilds the message from text + editable attachment
|
||||
// blocks, which would silently drop workspace file references.
|
||||
// Until the edit flow preserves them, such messages are not
|
||||
// editable.
|
||||
if (messageHasWorkspaceFileReferences(message)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Concatenate text parts verbatim to match the server-side string_agg in
|
||||
// GetChatUserPromptsByChatID; parseMessageContent/appendText is for streaming and drops whitespace-only chunks.
|
||||
const text = (message.content ?? [])
|
||||
|
||||
@@ -95,6 +95,19 @@ describe("applyMessagePartToStreamState", () => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns prev for workspace file reference parts", () => {
|
||||
const prev = createEmptyStreamState();
|
||||
const result = applyMessagePartToStreamState(prev, {
|
||||
type: "workspace-file-reference",
|
||||
workspace_file_path: "/home/coder/.coder/chats/chat-1/files/data.csv",
|
||||
workspace_file_name: "data.csv",
|
||||
workspace_file_size: 42,
|
||||
workspace_file_workspace_id: "ws-1",
|
||||
});
|
||||
|
||||
expect(result).toBe(prev);
|
||||
});
|
||||
|
||||
it("creates tool call entry from tool-call part", () => {
|
||||
const result = applyMessagePartToStreamState(null, {
|
||||
type: "tool-call",
|
||||
|
||||
@@ -221,6 +221,9 @@ export const applyMessagePartToStreamState = (
|
||||
// Hook notices may arrive in durable message events, but not in
|
||||
// streaming part deltas.
|
||||
case "hook-notice":
|
||||
// workspace-file-reference parts only appear in persisted
|
||||
// user messages, never via SSE streaming.
|
||||
case "workspace-file-reference":
|
||||
return prev;
|
||||
default: {
|
||||
const _exhaustive: never = part;
|
||||
|
||||
@@ -55,6 +55,7 @@ export type RenderBlock =
|
||||
}
|
||||
| TypesGen.ChatFilePart
|
||||
| TypesGen.ChatFileReferencePart
|
||||
| TypesGen.ChatWorkspaceFileReferencePart
|
||||
| {
|
||||
type: "sources";
|
||||
sources: Array<{ url: string; title: string }>;
|
||||
|
||||
Reference in new issue
Block a user