Files
coder/coderd/x/chatd/recording.go
T
Michael Suchacz ae6013f9d5 refactor(coderd/x/chatd): extract the recording multipart parser and table its tests (#30954)
The bounded multipart loop in `stopAndStoreRecording` (part cap,
per-type size limits, the empty, duplicate and unknown-part skips, and
partial results on read errors) could only be tested through a
PostgreSQL-backed server and an agent mock. This PR moves the loop
unchanged into `readRecordingParts` and replaces five tests
(`TestStopAndStoreRecording_Oversized`, `_OversizedThumbnail`,
`_DuplicatePartsIgnored`, `_Empty` and `_UnknownPartIgnored`) with one
table test, `TestReadRecordingParts`, that streams parts through a pipe.

**Why it is safe**

- The loop body moves as is: same `maxParts`, limits, messages and skip
rules. The caller still reads parts only after the workspace lookup and
stores the video before the thumbnail. The kept
`TestStopAndStoreRecording_*` tests still cover storage.
- The table asserts exact video and thumbnail bytes for every case the
deleted tests covered. The unknown part now comes first, so it reaches
the unknown-type branch. New rows cover the part cap, a duplicate
thumbnail, video and thumbnail parts above the 1 MB unknown-type limit,
a video above the thumbnail limit, a thumbnail at exactly the thumbnail
limit, a read error and a canceled context.
- I ran 14 mutants of the guarded lines with `go test -overlay`: the
size check; each per-type limit raised by one or dropped, and the video
limit set to the thumbnail limit; the empty check; both duplicate
checks; the unknown-type branch; the part cap raised and lowered; the
context check; and the read-error branch. The deleted tests caught 2 and
the table catches all 14. Only `VideoAboveThumbnailLimit` catches the
video limit set to the thumbnail limit. Storage checks the file bytes,
so it rejected the deleted tests' zero-filled and empty fixtures whether
or not the parser accepted them.
- The latest commit adds `ThumbnailAtLimit`. With `go test -overlay`, it
catches two more mutants that the rest of the table misses: the size
check changed from `>` to `>=`, and the thumbnail limit lowered by one
byte. No row sends a video of exactly `workspacesdk.MaxRecordingSize`
bytes, because that needs another 100 MB part, so a video limit lowered
by one byte still passes.

**Review focus**

The `break` and `continue` paths now end at `return videoData,
thumbnailData` instead of falling into the storage code. The
canceled-context and read-error rows cover both.

**Validation**

- `go test ./coderd/x/chatd/ -run
'TestStopAndStoreRecording|TestWaitAgent|TestReadRecordingParts|TestRecordingBoundary'
-count=1 -p 4 -parallel 4`: ok, and ok with `-race`
- `go test -race ./coderd/x/chatd/ -run '^TestReadRecordingParts$'
-count=10`: ok
- `go vet ./coderd/x/chatd/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack moves the recording response parsing out of
`stopAndStoreRecording` into two functions with table tests, and drops
seven PostgreSQL-backed parse tests.

1. #30953 extract the recording boundary parser and table its tests
2. #30954 extract the recording multipart parser and table its tests
(this PR, +202/-277 in 2 files)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-27 23:10:37 +00:00

268 lines
7.5 KiB
Go

package chatd
import (
"context"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"github.com/google/uuid"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/x/chatd/chattool"
"github.com/coder/coder/v2/coderd/x/chatfiles"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
type recordingResult struct {
recordingFileID string
thumbnailFileID string
}
// stopAndStoreRecording stops the desktop recording, downloads the
// multipart response containing the MP4 and optional thumbnail, and
// stores them in chat_files. Only called when the subagent completed
// successfully. Returns file IDs on success, empty fields on any
// failure. All errors are logged but not propagated; recording is
// best-effort.
func (p *Server) stopAndStoreRecording(
ctx context.Context,
conn workspacesdk.AgentConn,
recordingID string,
parentChatID uuid.UUID,
ownerID uuid.UUID,
workspaceID uuid.NullUUID,
) recordingResult {
var result recordingResult
workspaceIDValue := ""
if workspaceID.Valid {
workspaceIDValue = workspaceID.UUID.String()
}
logger := p.logger.With(
slog.F("recording_id", recordingID),
slog.F("parent_chat_id", parentChatID.String()),
slog.F("workspace_id", workspaceIDValue),
)
select {
case p.recordingSem <- struct{}{}:
defer func() { <-p.recordingSem }()
case <-ctx.Done():
logger.Warn(ctx, "context canceled waiting for recording semaphore", slog.Error(ctx.Err()))
return result
}
resp, err := conn.StopDesktopRecording(ctx,
workspacesdk.StopDesktopRecordingRequest{RecordingID: recordingID})
if err != nil {
logger.Warn(ctx, "failed to stop desktop recording",
slog.Error(err))
return result
}
defer resp.Body.Close()
boundary, ok := recordingBoundary(ctx, logger, resp.ContentType)
if !ok {
return result
}
if !workspaceID.Valid {
logger.Warn(ctx, "chat has no workspace, cannot store recording")
return result
}
// The chatd actor is used here because the recording is stored on
// behalf of the chat system, not a specific user request.
//nolint:gocritic // AsChatd is required to read the workspace for org lookup.
chatdCtx := dbauthz.AsChatd(ctx)
ws, err := p.db.GetWorkspaceByID(chatdCtx, workspaceID.UUID)
if err != nil {
logger.Warn(ctx, "failed to resolve workspace for recording",
slog.Error(err))
return result
}
videoData, thumbnailData := readRecordingParts(ctx, logger, resp.Body, boundary)
// Second pass: store the collected data in the database.
if videoData != nil {
attachment, err := p.storeRecordingArtifact(
chatdCtx,
parentChatID,
ownerID,
ws.OrganizationID,
fmt.Sprintf("recording-%s.mp4", p.clock.Now().UTC().Format("2006-01-02T15-04-05Z")),
"video/mp4",
videoData,
)
if err != nil {
logger.Warn(ctx, "failed to store recording in database",
slog.Error(err))
} else {
result.recordingFileID = attachment.FileID.String()
}
}
// The thumbnail is linked in its own transaction, so at a cap of one
// it would evict the recording that was just stored.
if thumbnailData != nil && result.recordingFileID != "" && p.chatLimits.MaxAttachmentsPerChat > 1 {
attachment, err := p.storeRecordingArtifact(
chatdCtx,
parentChatID,
ownerID,
ws.OrganizationID,
fmt.Sprintf("thumbnail-%s.jpg", p.clock.Now().UTC().Format("2006-01-02T15-04-05Z")),
"image/jpeg",
thumbnailData,
)
if err != nil {
logger.Warn(ctx, "failed to store thumbnail in database",
slog.Error(err))
} else {
result.thumbnailFileID = attachment.FileID.String()
}
}
return result
}
func readRecordingParts(ctx context.Context, logger slog.Logger, body io.Reader, boundary string) (videoData, thumbnailData []byte) {
mr := multipart.NewReader(body, boundary)
// Context cancellation is checked between parts. Within a
// part read, cancellation relies on Go's HTTP transport closing
// the underlying connection when the context is done, which
// interrupts the blocked io.ReadAll.
// First pass: parse all multipart parts into memory.
// The agent sends at most two parts: one video/mp4 and one
// optional image/jpeg thumbnail. Cap the number of parts to
// prevent a malicious or broken agent from forcing the server
// into an unbounded parsing loop.
const maxParts = 2
for range maxParts {
if ctx.Err() != nil {
logger.Warn(ctx, "context canceled while reading recording parts", slog.Error(ctx.Err()))
break
}
part, err := mr.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
logger.Warn(ctx, "error reading next multipart part", slog.Error(err))
break
}
contentType := part.Header.Get("Content-Type")
// Select the read limit based on content type so that
// thumbnails (image/jpeg) do not allocate up to
// MaxRecordingSize (100 MB) before the size check rejects
// them. Unknown types use a small default since they are
// discarded below.
maxSize := int64(1 << 20) // 1 MB default for unknown types
switch contentType {
case "video/mp4":
maxSize = int64(workspacesdk.MaxRecordingSize)
case "image/jpeg":
maxSize = int64(workspacesdk.MaxThumbnailSize)
}
data, err := io.ReadAll(io.LimitReader(part, maxSize+1))
if err != nil {
logger.Warn(ctx, "failed to read recording part data",
slog.F("content_type", contentType),
slog.Error(err))
continue
}
if int64(len(data)) > maxSize {
logger.Warn(ctx, "recording part exceeds maximum size, skipping",
slog.F("content_type", contentType),
slog.F("size", len(data)),
slog.F("max_size", maxSize))
continue
}
if len(data) == 0 {
logger.Warn(ctx, "recording part is empty, skipping",
slog.F("content_type", contentType))
continue
}
switch contentType {
case "video/mp4":
if videoData != nil {
logger.Warn(ctx, "duplicate video/mp4 part in recording response, skipping")
continue
}
videoData = data
case "image/jpeg":
if thumbnailData != nil {
logger.Warn(ctx, "duplicate image/jpeg part in recording response, skipping")
continue
}
thumbnailData = data
default:
logger.Debug(ctx, "skipping unknown part content type",
slog.F("content_type", contentType))
}
}
return videoData, thumbnailData
}
func recordingBoundary(ctx context.Context, logger slog.Logger, contentType string) (string, bool) {
_, params, err := mime.ParseMediaType(contentType)
if err != nil {
logger.Warn(ctx, "failed to parse content type from recording response",
slog.F("content_type", contentType),
slog.Error(err))
return "", false
}
boundary := params["boundary"]
if boundary == "" {
logger.Warn(ctx, "missing boundary in recording response content type",
slog.F("content_type", contentType))
return "", false
}
return boundary, true
}
func (p *Server) storeRecordingArtifact(
ctx context.Context,
chatID uuid.UUID,
ownerID uuid.UUID,
organizationID uuid.UUID,
name string,
mediaType string,
data []byte,
) (chattool.AttachmentMetadata, error) {
storedName, verifiedMediaType, err := chatfiles.PrepareRecordingArtifact(name, mediaType, data)
if err != nil {
return chattool.AttachmentMetadata{}, err
}
var attachment chattool.AttachmentMetadata
err = p.db.InTx(func(tx database.Store) error {
var err error
attachment, err = storeLinkedChatFileTx(
ctx,
tx,
chatID,
ownerID,
organizationID,
storedName,
verifiedMediaType,
data,
p.chatLimits.MaxAttachmentsPerChat,
)
return err
}, database.DefaultTXOptions().WithID("store_recording_artifact"))
if err != nil {
return chattool.AttachmentMetadata{}, err
}
return attachment, nil
}