mirror of
https://github.com/coder/coder.git
synced 2026-09-22 21:22:17 +08:00
## Problem
Workspace context surfaced in chat (Coder Agents) is incomplete and racy
on a fresh boot:
- The context panel is missing personal skills (only repo-level skills
under `.claude/skills` show up).
- The MCP section lists `.mcp.json` files but no MCP servers are
registered.
- The Issues panel reports instruction files as unreadable, e.g.
`CLAUDE.md (file: unreadable)` and `.cursorrules (file: unreadable)`
with `symlink resolve: lstat .../AGENTS.md: no such file or directory`.
## Root cause
`agentcontext.Manager` collected and pushed context too eagerly:
- `NewManager` ran an eager resolve at agent `init()`.
- `RunPush` starts as a normal connection routine (`startAgentAPI210`)
with no lifecycle gating, so the first snapshot was pushed
(`Initial=true`) as soon as the agent API connected.
Both happened **before startup scripts finish** and before the lifecycle
reaches `ready`. At that point:
- `CLAUDE.md` / `.cursorrules` symlinks to `AGENTS.md` don't resolve
yet, so `EvalSymlinks` fails and the resolver emits `StatusUnreadable`
"symlink resolve" issues.
- Personal skills haven't synced yet, so they're missing.
- MCP servers connect via `mcpManager.Reload(...)` only **after**
`ready`, so only `.mcp.json` configs appear, with no servers.
That partial, error-laden snapshot is persisted by coderd and can
hydrate a chat.
## Fix
Gate `agentcontext.Manager` until the agent is ready, unconditionally:
- The Manager always starts gated. `NewManager` leaves the zero-value
(version 0) snapshot in place and never walks the filesystem; `RunPush`
withholds version-0 snapshots, so nothing reaches coderd.
- The agent calls `Manager.SetReady()` from the lifecycle transition in
`handleManifest`, right after startup scripts finish (`ready`, or
terminal `start_error` / `start_timeout` so a failed startup still
surfaces whatever context exists).
- On `SetReady`, the Manager performs the first real resolve (version 1)
and broadcasts it; `RunPush` ships it with `Initial=true`. Later changes
(MCP connect, skill edits) re-resolve and push as before.
Eager resolution before `ready` was the bug, not a mode worth
preserving, so the gate is always on rather than an opt-in option. This
aligns the agent-side push with chatd, which already waits for agent
readiness before loading context. No proto/coderd/DB changes: coderd
simply never receives a pre-ready snapshot.
<details>
<summary>Design notes & decisions</summary>
- **Unconditional, not opt-in.** An earlier iteration added the gate as
an opt-in `ManagerOptions.GateUntilReady`. Since the eager
resolve-on-construct was the defect, the option, the eager first
resolve, and the now-dead `resolveLocked` helper were all removed; the
Manager is always gated until `SetReady`.
- **Version 0 is the pre-ready sentinel.** The gated placeholder is just
the zero-value snapshot (version 0); the first real resolve is version
1, so the push loop withholds anything at version 0. An earlier revision
carried a dedicated `Snapshot.Initializing` bool plus an HTTP `/resync`
field, but the push loop was the only consumer and nothing read the HTTP
field, so both were dropped.
- **Defer, don't retry symlinks.** Transient "unreadable" symlinks are
an artifact of collecting before checkout. Deferring until `ready` fixes
all three symptom classes at once and avoids masking genuine post-ready
errors (a broken symlink at `ready` is still reported).
- **Release on terminal startup states too** (`start_error`,
`start_timeout`), so a failed startup still surfaces whatever context
exists instead of gating forever. On reconnect the Manager instance is
reused and stays ready.
</details>
## Tests
- `agentcontext.TestManager_WithholdsCollectionUntilReady` simulates
collection running before startup finishes (broken `CLAUDE.md` /
`.cursorrules` -> `AGENTS.md` symlinks): asserts the gated snapshot is
the empty version-0 placeholder with no resources and no `unreadable`
issues, and that after `SetReady` (target now present) the inventory
resolves cleanly to a single instruction file with no spurious issues.
- `agentcontext.TestRunPush_WaitsForReady` asserts the push loop ships
nothing while gated even when content exists, then ships the full
inventory with `Initial=true` after `SetReady`.
- `agentcontext.TestManager_SetReadyIsIdempotent` covers the version-0
placeholder before ready, the single resolve to version 1 on `SetReady`,
and idempotency across repeated calls.
- Updated `agent.TestAgent_ContextStatePushed`: the first push now
already contains `AGENTS.md` with `Initial=true` and no `UNREADABLE`
resources (no pre-startup empty/partial push).
Validated on the changed packages: `go test -race
./agent/agentcontext/...`, `go test ./agent/ -run
TestAgent_ContextStatePushed`, `golangci-lint run`, `go vet`, `gofmt`
(all clean).
---
🤖 Generated by Coder Agents on behalf of @kylecarbs.
211 lines
5.8 KiB
Go
211 lines
5.8 KiB
Go
package agentcontext
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/quartz"
|
|
)
|
|
|
|
// PushRequest is the wire-format-independent payload the
|
|
// Manager hands to a Pusher. It mirrors the protobuf
|
|
// PushContextStateRequest message reserved in the RFC.
|
|
//
|
|
// Keeping the shape in plain Go lets this package compile
|
|
// without bumping the drpc proto version. The follow-up
|
|
// integration change can add a thin adapter that converts
|
|
// PushRequest to proto and back.
|
|
type PushRequest struct {
|
|
Version uint64
|
|
AggregateHash [32]byte
|
|
Resources []Resource
|
|
Initial bool
|
|
SnapshotError string
|
|
}
|
|
|
|
// PushResponse is the wire-format-independent return value of
|
|
// a push.
|
|
type PushResponse struct {
|
|
Accepted bool
|
|
}
|
|
|
|
// Pusher delivers snapshots to coderd. Concrete implementations
|
|
// wrap a drpc client (Agent API v2.10 and later) or, in tests,
|
|
// a recording in-memory fake.
|
|
//
|
|
// PushContextState must respect ctx cancellation; the Manager
|
|
// retries on transient errors with backoff but stops on
|
|
// ErrPushUnimplemented.
|
|
type Pusher interface {
|
|
PushContextState(ctx context.Context, req *PushRequest) (*PushResponse, error)
|
|
}
|
|
|
|
// ErrPushUnimplemented signals that the coderd peer does not
|
|
// implement PushContextState. RunPush stops pushing for the
|
|
// remainder of the connection.
|
|
var ErrPushUnimplemented = xerrors.New("agentcontext: PushContextState unimplemented")
|
|
|
|
// Default backoff timings for pushWithRetry. Exposed as named
|
|
// constants (rather than inline literals) so godoc shows them
|
|
// and a second push loop, if it ever appears, can reuse them.
|
|
const (
|
|
DefaultPushInitialBackoff = 250 * time.Millisecond
|
|
DefaultPushMaxBackoff = 30 * time.Second
|
|
)
|
|
|
|
// PushOptions parameterizes RunPush.
|
|
type PushOptions struct {
|
|
// Logger receives push success/failure diagnostics.
|
|
Logger slog.Logger
|
|
// InitialBackoff is the wait before the first retry.
|
|
// Default 250ms.
|
|
InitialBackoff time.Duration
|
|
// MaxBackoff caps the retry wait. Default 30s.
|
|
MaxBackoff time.Duration
|
|
// Clock is the time source for retry backoffs. Optional;
|
|
// defaults to the Manager's clock so tests can trap waits
|
|
// with quartz instead of real sleeps.
|
|
Clock quartz.Clock
|
|
}
|
|
|
|
// RunPush ships the current snapshot to the Pusher, then ships
|
|
// every subsequent snapshot whenever the Manager broadcasts a
|
|
// change. RunPush returns when ctx is canceled, when the
|
|
// Manager is closed, or when the Pusher signals
|
|
// ErrPushUnimplemented.
|
|
//
|
|
// The first push is always sent with Initial=true so coderd can
|
|
// distinguish a fresh boot from a drift event.
|
|
func (m *Manager) RunPush(ctx context.Context, p Pusher, opts PushOptions) error {
|
|
if p == nil {
|
|
return xerrors.New("agentcontext: Pusher is required")
|
|
}
|
|
logger := opts.Logger
|
|
initialBackoff := opts.InitialBackoff
|
|
if initialBackoff <= 0 {
|
|
initialBackoff = DefaultPushInitialBackoff
|
|
}
|
|
maxBackoff := opts.MaxBackoff
|
|
if maxBackoff <= 0 {
|
|
maxBackoff = DefaultPushMaxBackoff
|
|
}
|
|
clock := opts.Clock
|
|
if clock == nil {
|
|
clock = m.clock
|
|
}
|
|
|
|
changes, unsub := m.SubscribeChanges()
|
|
defer unsub()
|
|
|
|
// Until SetReady the snapshot is version 0: wait, don't push it.
|
|
initial := true
|
|
for {
|
|
snap := m.Snapshot()
|
|
if snap.Version == 0 {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-m.closedCh:
|
|
return nil
|
|
case <-changes:
|
|
}
|
|
continue
|
|
}
|
|
req := snapshotToPushRequest(snap, initial)
|
|
|
|
err := pushWithRetry(ctx, p, req, initialBackoff, maxBackoff, clock, logger)
|
|
switch {
|
|
case err == nil:
|
|
initial = false
|
|
case errors.Is(err, ErrPushUnimplemented):
|
|
logger.Warn(ctx, "coderd peer does not implement PushContextState; stopping")
|
|
return nil
|
|
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
|
|
return ctx.Err()
|
|
default:
|
|
// Should be unreachable: pushWithRetry only
|
|
// returns terminal errors. Log and continue.
|
|
logger.Warn(ctx, "push terminated with non-retried error", slog.Error(err))
|
|
}
|
|
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-m.closedCh:
|
|
return nil
|
|
case <-changes:
|
|
// Shutdown comes from closedCh or ctx; the
|
|
// subscriber channel is never closed by
|
|
// SubscribeChanges.
|
|
}
|
|
}
|
|
}
|
|
|
|
// pushWithRetry retries transient errors with exponential
|
|
// backoff capped at maxBackoff. The retry loop exits when:
|
|
//
|
|
// - ctx is canceled (returns ctx.Err()).
|
|
// - The Pusher returns nil (success).
|
|
// - The Pusher returns ErrPushUnimplemented (propagated).
|
|
func pushWithRetry(
|
|
ctx context.Context,
|
|
p Pusher,
|
|
req *PushRequest,
|
|
initialBackoff, maxBackoff time.Duration,
|
|
clock quartz.Clock,
|
|
logger slog.Logger,
|
|
) error {
|
|
backoff := initialBackoff
|
|
for {
|
|
resp, err := p.PushContextState(ctx, req)
|
|
if err == nil {
|
|
if resp != nil && !resp.Accepted {
|
|
// Out-of-order or replayed push. Do not
|
|
// retry; the next change will redeliver
|
|
// the snapshot with a higher version.
|
|
logger.Debug(ctx, "push rejected, awaiting next change",
|
|
slog.F("version", req.Version))
|
|
}
|
|
return nil
|
|
}
|
|
if errors.Is(err, ErrPushUnimplemented) {
|
|
return err
|
|
}
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
return err
|
|
}
|
|
logger.Warn(ctx, "push failed, retrying",
|
|
slog.F("version", req.Version),
|
|
slog.F("backoff", backoff),
|
|
slog.Error(err))
|
|
timer := clock.NewTimer(backoff)
|
|
select {
|
|
case <-ctx.Done():
|
|
timer.Stop()
|
|
return ctx.Err()
|
|
case <-timer.C:
|
|
}
|
|
backoff *= 2
|
|
if backoff > maxBackoff {
|
|
backoff = maxBackoff
|
|
}
|
|
}
|
|
}
|
|
|
|
// snapshotToPushRequest copies the Snapshot into the wire
|
|
// representation. The Resources slice is reused; callers must
|
|
// not mutate it.
|
|
func snapshotToPushRequest(s Snapshot, initial bool) *PushRequest {
|
|
return &PushRequest{
|
|
Version: s.Version,
|
|
AggregateHash: s.AggregateHash,
|
|
Resources: s.Resources,
|
|
Initial: initial,
|
|
SnapshotError: s.SnapshotError,
|
|
}
|
|
}
|