Files
coder/coderd/aibridge/factory_test.go
T
Cian Johnston 19076beb8d feat: attribute AI Gateway usage to workspaces (#29235)
- Adds nullable `workspace_id` to AI Gateway interceptions without a
foreign key or index.
- Derives direct attribution from strictly parsed server-minted workspace
session-token names, excluding user-created tokens and validating the
embedded owner.
- Derives delegated Coder Agents attribution from the persisted chat
workspace ID.
- Records `workspace_id` through the additive v1.3 gateway protocol and
structured interception logs.
- Exposes attribution in session details through
`interception_attributions`, including tool-less interceptions and null
values for unknown attribution.

Closes AIGOV-637

Generated by Coder Agents.
2026-09-18 15:22:02 +01:00

65 lines
1.7 KiB
Go

package aibridge_test
import (
"context"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/aibridge"
)
func TestAttributionContext(t *testing.T) {
t.Parallel()
wsID := uuid.New()
t.Run("WithWorkspace", func(t *testing.T) {
t.Parallel()
attr := aibridge.Attribution{WorkspaceID: wsID}
ctx := aibridge.WithAttribution(context.Background(), attr)
got, ok := aibridge.AttributionFromContext(ctx)
require.True(t, ok)
require.Equal(t, attr, got)
})
t.Run("NoAttribution", func(t *testing.T) {
t.Parallel()
_, ok := aibridge.AttributionFromContext(context.Background())
require.False(t, ok)
})
t.Run("ZeroWorkspaceID", func(t *testing.T) {
t.Parallel()
// An Attribution with a zero WorkspaceID is not considered set.
attr := aibridge.Attribution{WorkspaceID: uuid.Nil}
ctx := aibridge.WithAttribution(context.Background(), attr)
_, ok := aibridge.AttributionFromContext(ctx)
require.False(t, ok, "Attribution with zero WorkspaceID must not be considered set")
})
t.Run("OverwrittenByInnerContext", func(t *testing.T) {
t.Parallel()
// A child context can shadow the parent's Attribution without
// mutating it, ensuring per-request immutability.
parent := aibridge.Attribution{WorkspaceID: uuid.New()}
child := aibridge.Attribution{WorkspaceID: wsID}
pCtx := aibridge.WithAttribution(context.Background(), parent)
cCtx := aibridge.WithAttribution(pCtx, child)
gotParent, ok := aibridge.AttributionFromContext(pCtx)
require.True(t, ok)
require.Equal(t, parent, gotParent)
gotChild, ok := aibridge.AttributionFromContext(cCtx)
require.True(t, ok)
require.Equal(t, child, gotChild)
})
}