mirror of
https://github.com/coder/coder.git
synced 2026-09-21 20:51:01 +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.
71 lines
2.4 KiB
Go
71 lines
2.4 KiB
Go
package agent_test
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/coder/coder/v2/agent"
|
|
"github.com/coder/coder/v2/agent/agentcontextconfig"
|
|
"github.com/coder/coder/v2/agent/agenttest"
|
|
agentproto "github.com/coder/coder/v2/agent/proto"
|
|
"github.com/coder/coder/v2/codersdk/agentsdk"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
// TestAgent_ContextStatePushed verifies the agent pushes its workspace
|
|
// context over the v2.10 PushContextState RPC, and that the readiness
|
|
// gate (SetReady, wired to the lifecycle transition) holds the push
|
|
// until startup completes. The first push therefore already contains
|
|
// the seeded AGENTS.md with Initial=true and no "unreadable" issues.
|
|
func TestAgent_ContextStatePushed(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
dir := t.TempDir()
|
|
require.NoError(t,
|
|
os.WriteFile(filepath.Join(dir, "AGENTS.md"), []byte("test rules"), 0o600))
|
|
|
|
//nolint:dogsled // setupAgent returns a wide tuple; we only care about the client.
|
|
_, client, _, _, _ := setupAgent(t,
|
|
agentsdk.Manifest{Directory: dir},
|
|
0,
|
|
func(_ *agenttest.Client, opts *agent.Options) {
|
|
opts.ContextConfig = agentcontextconfig.Config{}
|
|
},
|
|
)
|
|
|
|
// The push is gated until the agent reaches lifecycle ready. Wait
|
|
// for that first push to land.
|
|
var pushes []*agentproto.PushContextStateRequest
|
|
require.Eventually(t, func() bool {
|
|
pushes = client.ContextStatePushes()
|
|
return len(pushes) > 0
|
|
}, testutil.WaitMedium, testutil.IntervalFast,
|
|
"expected a context snapshot push after startup; got %d pushes", len(pushes))
|
|
|
|
first := pushes[0]
|
|
assert.True(t, first.GetInitial(), "first push must carry Initial=true")
|
|
assert.NotEmpty(t, first.GetAggregateHash(), "aggregate_hash must be populated")
|
|
|
|
// The first push must already reflect the ready workspace: the
|
|
// seeded AGENTS.md is present and no resource is UNREADABLE.
|
|
var foundAgents bool
|
|
for _, r := range first.GetResources() {
|
|
if r.GetInstructionFile() != nil &&
|
|
filepath.Base(r.GetSource()) == "AGENTS.md" {
|
|
foundAgents = true
|
|
}
|
|
assert.NotEqualf(t, agentproto.ContextResource_UNREADABLE, r.GetStatus(),
|
|
"no resource should be UNREADABLE in the post-ready snapshot: %s", r.GetSource())
|
|
}
|
|
assert.True(t, foundAgents, "first push must already include the seeded AGENTS.md")
|
|
|
|
// Subsequent pushes must not be Initial.
|
|
for _, p := range pushes[1:] {
|
|
assert.False(t, p.GetInitial(), "only the first push must be Initial")
|
|
}
|
|
}
|