Skip to content

feat(coderd/chatd): unify chat storage on SDK parts and fix file-reference rendering - #22958

Merged
mafredri merged 13 commits into
mainfrom
mafredri/feat-unify-chat-storage
Mar 13, 2026
Merged

mafredri merged 13 commits into
mainfrom
mafredri/feat-unify-chat-storage

Conversation

@mafredri

@mafredri mafredri commented Mar 11, 2026 •

Copy link
Copy Markdown
Member

File-reference parts in user messages were flattened to TextContent at write time because fantasy has no file-reference content type. The frontend never saw them as structured parts.

This moves all write paths (user, assistant, tool) from fantasy envelope format to codersdk.ChatMessagePart. The streaming layer (chatloop) is untouched, the conversion happens at the serialization boundary in persistStep.

Old rows are still readable. ParseContent uses a structural heuristic (isFantasyEnvelopeFormat) to distinguish legacy envelopes from SDK parts. We chose this over try/fallback because fantasy envelopes partially unmarshal into ChatMessagePart (the type field matches) while silently losing content. A guard test enforces that no SDK part can produce the envelope shape.

This is forward-only: new rows are unreadable by old code. Chat is behind a feature flag so rollback risk is contained.

Also adds a typed ChatMessageRole to replace raw strings and fantasy.MessageRole* casts at the persistence boundary. The type covers ChatMessage.Role, ChatStreamMessagePart.Role, the PublishMessagePart callback chain, and all DB write sites. fantasy.MessageRole* remains only where we build fantasy.Message structs for LLM dispatch.

Separately, ProviderMetadata was leaking to SSE clients via publishMessagePart. StripInternal now runs on both the SSE and REST paths, covering this.

Other cleanup:

  • Old db2sdk.contentBlockToPart silently dropped metadata on text/reasoning/tool-call content. New code preserves it.
  • providerMetadataToOptions now logs warnings instead of silently returning nil.
  • db2sdk shrinks from ~250 lines of parallel conversion to ~15 lines delegating to chatprompt.ParseContent(), removing the fantasy import entirely.

Follow-up: content_version column to replace the structural heuristic, and a Postgres enum for chat_messages.role to eliminate string() casts at the DB boundary. Both touch the same table and could ship together.

Refs #22821

@mafredri
mafredri force-pushed the mafredri/feat-unify-chat-storage branch 2 times, most recently from f91f256 to 4ba3848 Compare March 12, 2026 16:52
mafredri added 10 commits March 13, 2026 10:56
Switch ParseContent to return []codersdk.ChatMessagePart with
role-aware parsing:
- system: JSON string → single text part
- assistant: try SDK parts first, fall back to fantasy envelope
- tool: try SDK parts first, fall back to legacy tool result rows
- user: structural heuristic (isLegacyUserContentFormat) to
  distinguish fantasy envelope from SDK parts

Rewrite ConvertMessagesWithFiles to use ParseContent (SDK parts)
and partsToMessageParts for LLM dispatch.

Simplify db2sdk.chatMessageParts to delegate to ParseContent and
strip internal-only fields (ProviderMetadata, inline file Data).

Key additions:
- ProviderMetadata and ProviderExecuted fields on ChatMessagePart
- MarshalParts, marshalProviderMetadata, providerMetadataToOptions
- partsToMessageParts for SDK→fantasy conversion at LLM dispatch
- isLegacyUserContentFormat for format discrimination
- PartFromContent now preserves ProviderMetadata and ProviderExecuted

Removals:
- extractFileIDs, patchFileContent, ToMessageParts (replaced by
  partsToMessageParts)
- toToolResultPart method (replaced by toolResultPartToMessagePart)
- parseSystemContent (inlined into parseSystemRole)
- db2sdk: parseContentBlocks, contentBlockToPart, parseSystemContent,
  toolResultOutputToRawJSON, toolResultOutputIsError

Refs #22821
Change createChatInputFromParts to return []codersdk.ChatMessagePart
instead of ([]fantasy.Content, map[int]uuid.UUID). File-reference
input parts are now preserved as structured ChatMessagePart with
type file-reference instead of being flattened to fantasy.TextContent.
This is the commit that fixes the file-reference rendering bug.

Update CreateOptions, SendMessageOptions, EditMessageOptions to use
[]codersdk.ChatMessagePart. All three call MarshalParts instead of
MarshalContent.

Update subagent.go callers to build SDK parts directly.

Refs #22821
Change persistStep to convert fantasy.Content to ChatMessagePart via
PartFromContent before serializing with MarshalParts. The streaming
accumulation layer (chatloop) is untouched, only the final
serialization step changes.

Change persistChatContextSummary to build ChatMessagePart directly
and serialize via MarshalParts instead of using MarshalContent and
MarshalToolResult.

Remove MarshalToolResultContent, injectFileID, marshalContentBlock
(no longer needed). MarshalContent is retained for test fixtures
that create legacy-format DB rows.

Refs #22821
…at detection

Replace the try/fallback approach in parseAssistantRole with the same
structural heuristic used for user messages. The try/fallback relied
on json.Unmarshal failing when a JSON object hits a []byte field,
which is a brittle invariant tied to Go's decoder behavior. If Data
were ever changed to json.RawMessage, legacy assistant messages would
silently parse with correct Type but empty Text.

Rename isLegacyUserContentFormat to isFantasyEnvelopeFormat since
it's now shared between user and assistant parsing paths.

Add TestSDKPartsNeverProduceFantasyEnvelopeShape guard test that
verifies no SDK part type serializes with a data field containing a
JSON object, protecting the structural invariant.

Refs #22821
Add tests covering the key risks of the storage unification:

- ParseContent backward compatibility: 13 cases covering every
  legacy and new format variant (system string, fantasy envelope
  text/file/reasoning/tool-call for user and assistant roles,
  legacy tool result rows, new SDK parts for all roles)
- ProviderMetadata round-trip: legacy fantasy DB row with Anthropic
  cache hints → ParseContent → SDK part → ConvertMessagesWithFiles
  → fantasy part with typed ProviderOptions. Verifies the
  highest-risk data path.
- File-reference preservation: MarshalParts → ParseContent round-trip
  with all fields intact, plus LLM dispatch producing TextPart
- Assistant write round-trip: PartFromContent → MarshalParts → DB →
  ParseContent → ConvertMessagesWithFiles with ProviderMetadata
  surviving the full cycle
- Mixed-format conversation: realistic post-deploy scenario with
  system (string), old user (fantasy+file_id), old assistant
  (fantasy tool-call), old tool (result rows), new user
  (SDK+file-reference), new assistant (SDK+metadata) in a single
  ConvertMessagesWithFiles call

Refs #22821
…-trip test

Remove 'Internal only' from ProviderExecuted comment since the
streaming path already exposes it to frontends via
ChatStreamMessagePart. The field indicates whether the LLM provider
executed a tool call (e.g. Anthropic computer use), which is useful
for UI rendering.

Add TestQueuedMessageRoundTrip covering the queue → promote cycle:
MarshalParts → db2sdk.ChatQueuedMessage (display while queued) →
ParseContent (after promote) → ConvertMessagesWithFiles (LLM
dispatch). Verifies file-reference parts survive all three stages.

Refs #22821
Add typescript:"-" tag to ChatMessagePart.ProviderMetadata. This
field is always stripped to nil by db2sdk before API responses, so
it should not appear in the generated TypeScript types. The json tag
is retained for internal DB serialization via MarshalParts.
TestChatMessageWithFileReferences subtests previously expected
file-reference input to be stored as ChatMessagePartTypeText with
formatted text. Now that the write path preserves file-reference
parts as structured ChatMessagePartTypeFileReference, update all
subtests to check for the correct part type and structured fields
(FileName, StartLine, EndLine, Content).

This is the observable behavior change from the storage unification:
the API now returns typed file-reference parts that the frontend
can render as styled chips, instead of plain text.

Refs #22821
…ructors

ProviderMetadata was leaking to clients via SSE message_part events.
PartFromContent populates it for DB persistence fidelity, but
publishMessagePart passed parts to clients with no stripping.

Add StripInternal() to ChatMessagePart, centralizing the "which
fields are internal" decision. Use it in both db2sdk.chatMessageParts
(REST) and publishMessagePart (SSE) to ensure consistent stripping.

Add missing constructors ChatMessageFile, ChatMessageFileReference,
and ChatMessageSource, completing the set for all 7 part types.
Update createChatInputFromParts call sites and 10 enterprise test
sites to use constructors instead of inline struct literals.
@mafredri
mafredri force-pushed the mafredri/feat-unify-chat-storage branch from 4ba3848 to d92161f Compare March 13, 2026 11:05
Add missing backward-compat tests for ParseContent:
- user/plain_string: bare JSON string format (very old)
- assistant/fantasy_source: legacy SourceContent envelope

Remove dead tc := tc loop variable shadow (Go 1.22+).

Document in StripInternal why ArgsDelta and ResultDelta are
intentionally preserved (consumed by frontend via SSE).
@mafredri
mafredri force-pushed the mafredri/feat-unify-chat-storage branch 2 times, most recently from 197cd81 to 4929d83 Compare March 13, 2026 13:40
Add ChatMessageRole type and constants (System, User, Assistant,
Tool) to codersdk, replacing magic strings and fantasy.MessageRole
casts at the persistence/parsing boundary.

ParseContent now takes ChatMessageRole instead of string. Call
sites in chatd, quickgen, subagent, and db2sdk cast the DB string
at the boundary. This removes the fantasy import from db2sdk
entirely.

Also fixes MarshalToolResult doc comment (test-only, not
production) and adds TestParseContent_ErrorPaths covering null
content, unknown role, and malformed JSON for all four roles.
@mafredri
mafredri force-pushed the mafredri/feat-unify-chat-storage branch from 4929d83 to 516309f Compare March 13, 2026 13:44
…hat-storage

# Conflicts:
#	coderd/chatd/chatd_test.go
#	coderd/chats_test.go
@mafredri
mafredri marked this pull request as ready for review March 13, 2026 14:10
@mafredri
mafredri requested review from johnstcn and kylecarbs March 13, 2026 14:11

@kylecarbs kylecarbs left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Lovely you did backwards compatibility. Hopefully we can remove that in a week or two ish!

Comment thread codersdk/chats.go
Comment on lines +97 to +102
// WARNING: This type is both an API wire type and a database
// persistence format. Its JSON layout is stored in the
// chat_messages.content column. Field additions, renames, type
// changes, and omitempty behavior all affect backward-compatible
// deserialization of stored rows. Treat changes to this struct
// with the same care as a database migration.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lovely warning!

@johnstcn johnstcn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:shipit:

@mafredri
mafredri merged commit bdbcd34 into main Mar 13, 2026
35 checks passed
@mafredri
mafredri deleted the mafredri/feat-unify-chat-storage branch March 13, 2026 15:53
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 13, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants