fix(agent/agentgit): re-resolve chat paths on refresh (#30675)

A git watch `refresh` only rescanned the repos already being watched. A
path recorded before its repo existed, for example before `git init`, or
a repo that was deleted and recreated, stayed hidden until the client
reconnected, so a page reload showed repos the refresh button didn't.

Refresh now resolves the chat's paths again, as a new connection does.
The first scan of a connection is also sent even when no repos are
watched, so a client can replace state left over from an earlier
connection; later scans with no repos still send nothing.

### Before


https://github.com/user-attachments/assets/33bf9046-0448-4537-9a97-c97f51e1cc39

### After


https://github.com/user-attachments/assets/82b15d03-6460-4fe0-b5e7-b4bafbbd72d1

<details>
<summary>Decision log</summary>

The git panel's refresh button should show everything a page reload
would. Investigation found five ways it didn't, each fixed in its own PR
on the current `changes` protocol:

1. `execute` without a workdir didn't record the directory the process
ran in (`agent/agentproc`).
2. Refresh only rescanned repos already being watched, so a repo created
or recreated after its path was recorded stayed hidden
(`agent/agentgit`). A connection with no repos also got no first
message.
3. After a git watch reconnect, the new full state was merged into the
previous connection's map, so deleted repos stayed visible
(`useGitWatcher`).
4. A chat watch reconnect didn't refetch the open chat, so missed
`diff_status_change` events were lost (`AgentsPageLayout`).
5. Refresh didn't refetch the chat, whose diff statuses back the PR
tabs, and was disabled until git context existed (`GitPanel`,
`AgentChatPageView`).

Considered and deferred: a snapshot protocol with diffs fetched by hash,
which would keep large multi-repo diffs under the 4 MiB proxy read
limit, and making scans faster at scale. Neither is needed to fix
refresh, and together they made a single ~5900-line change that couldn't
be reviewed. The refresh spinner still runs for a fixed time, since
tying it to the response needs a request ID in the protocol.

</details>

---

_Generated by Coder Agents on behalf of @DanielleMaywood._
This commit is contained in:
Danielle Maywood authored and GitHub committed 2026-10-14 17:04:39 +01:00
1 parent 2b844aa649
commit e981ff4eec
3 files changed
+87 -15

No files matched your search

+8 -2
View File
@@ -69,6 +69,7 @@ type Handler struct {
repoRoots map[string]struct{} // watched repo roots
lastSnapshots map[string]repoSnapshot // last emitted snapshot per repo
lastScanAt time.Time // when the last scan completed
scanned bool // whether Scan has emitted a message
scanTrigger chan struct{} // buffered(1), poked by triggers
}
@@ -151,7 +152,10 @@ func (h *Handler) RequestScan() {
}
// Scan performs a scan of all subscribed repos and computes deltas
// against the previously emitted snapshots.
// against the previously emitted snapshots. The first scan always
// returns a message, even with no repos, so a new connection starts
// from a known state. Later scans return nil while no repos are
// subscribed.
func (h *Handler) Scan(ctx context.Context) *codersdk.WorkspaceAgentGitServerMessage {
if !h.gitAvailable() {
return nil
@@ -162,9 +166,10 @@ func (h *Handler) Scan(ctx context.Context) *codersdk.WorkspaceAgentGitServerMes
for r := range h.repoRoots {
roots = append(roots, r)
}
scanned := h.scanned
h.mu.Unlock()
if len(roots) == 0 {
if len(roots) == 0 && scanned {
return nil
}
@@ -231,6 +236,7 @@ func (h *Handler) Scan(ctx context.Context) *codersdk.WorkspaceAgentGitServerMes
}
h.lastScanAt = now
h.scanned = true
// Always emit when any root is subscribed. A no-delta scan sends
// ScannedAt + empty Repositories (omitted via omitempty) so the
+66 -5
View File
@@ -120,7 +120,9 @@ func TestSubscribeEmptyPaths(t *testing.T) {
ctx := context.Background()
msg := h.Scan(ctx)
require.Nil(t, msg, "scan should return nil with no repos")
require.NotNil(t, msg, "first scan should report the empty state")
require.Empty(t, msg.Repositories)
require.Nil(t, h.Scan(ctx), "later scans should return nil with no repos")
}
func TestScanReturnsRepoChanges(t *testing.T) {
@@ -356,10 +358,10 @@ func TestScanHeartbeatOnCleanRepo(t *testing.T) {
}
// TestScanNoHeartbeatWithoutSubscribedRoots pins that the heartbeat
// only fires when there is at least one subscribed repo. Before any
// subscribe call, Scan() must still short-circuit to nil so the
// WebSocket handler does not spam empty messages to a client that
// has not registered any paths yet.
// only fires when there is at least one subscribed repo. The first
// scan reports the empty state once; after that Scan() short-circuits
// to nil so the WebSocket handler does not spam empty messages to a
// client that has not registered any paths yet.
func TestScanNoHeartbeatWithoutSubscribedRoots(t *testing.T) {
t.Parallel()
@@ -367,6 +369,10 @@ func TestScanNoHeartbeatWithoutSubscribedRoots(t *testing.T) {
h := agentgit.NewHandler(logger)
msg := h.Scan(context.Background())
require.NotNil(t, msg, "first scan should report the empty state")
require.Empty(t, msg.Repositories)
msg = h.Scan(context.Background())
require.Nil(t, msg, "no subscribed roots should mean no heartbeat")
}
@@ -904,6 +910,44 @@ func TestWebSocketRefreshTriggersChanges(t *testing.T) {
require.NotEmpty(t, msg.Repositories)
}
// TestWebSocketRefreshResolvesNewRepo pins that refresh re-resolves
// the chat's paths, so a repo initialized after its path was recorded
// appears on refresh just as it would on a new connection.
func TestWebSocketRefreshResolvesNewRepo(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
dir := testutil.TempDirResolved(t)
file := filepath.Join(dir, "main.go")
require.NoError(t, os.WriteFile(file, []byte("package main\n"), 0o600))
ps := agentgit.NewPathStore()
chatID := uuid.New()
ps.AddPaths([]uuid.UUID{chatID}, []string{file})
mClock := quartz.NewMock(t)
stream := dialGitWatchWithPathStore(t, ps, chatID, agentgit.WithClock(mClock))
ch := stream.Chan()
// The path is not in a repo yet, but the connection still reports
// its initial empty state.
msg := recvMsg(ctx, t, ch)
require.Equal(t, codersdk.WorkspaceAgentGitServerMessageTypeChanges, msg.Type)
require.Empty(t, msg.Repositories)
gitCmd(t, dir, "init")
mClock.Advance(2 * time.Second).MustWait(ctx)
err := stream.Send(codersdk.WorkspaceAgentGitClientMessage{
Type: codersdk.WorkspaceAgentGitClientMessageTypeRefresh,
})
require.NoError(t, err)
msg = recvMsg(ctx, t, ch)
require.Len(t, msg.Repositories, 1)
require.Equal(t, dir, msg.Repositories[0].RepoRoot)
}
func TestWebSocketUnknownMessageType(t *testing.T) {
t.Parallel()
@@ -911,6 +955,11 @@ func TestWebSocketUnknownMessageType(t *testing.T) {
stream := dialGitWatch(t)
ch := stream.Chan()
// Every connection starts with its initial state, even with no repos.
initial := recvMsg(ctx, t, ch)
require.Equal(t, codersdk.WorkspaceAgentGitServerMessageTypeChanges, initial.Type)
require.Empty(t, initial.Repositories)
err := stream.Send(codersdk.WorkspaceAgentGitClientMessage{
Type: "bogus",
})
@@ -1324,6 +1373,12 @@ func TestE2E_WriteFileTriggersGitWatch(t *testing.T) {
stream := dialGitWatchWithPathStore(t, ps, chatID, agentgit.WithClock(mClock))
ch := stream.Chan()
// The connection reports its initial empty state first. Advance
// past the scan cooldown so the path update scans immediately.
initial := recvMsg(ctx, t, ch)
require.Empty(t, initial.Repositories)
mClock.Advance(2 * time.Second).MustWait(ctx)
// Simulate what HandleWriteFile does: add a path to the
// PathStore. This triggers a notification → subscribe → scan.
ps.AddPaths([]uuid.UUID{chatID}, []string{filepath.Join(repoDir, "newfile.go")})
@@ -1362,6 +1417,12 @@ func TestE2E_SubagentAncestorWatch(t *testing.T) {
stream := dialGitWatchWithPathStore(t, ps, parentChatID, agentgit.WithClock(mClock))
ch := stream.Chan()
// The connection reports its initial empty state first. Advance
// past the scan cooldown so the path update scans immediately.
initial := recvMsg(ctx, t, ch)
require.Empty(t, initial.Repositories)
mClock.Advance(2 * time.Second).MustWait(ctx)
// Simulate a tool call from the CHILD chat with the parent as
// ancestor. The PathStore propagates the paths to all ancestor
// chat IDs.
+13 -8
View File
@@ -88,8 +88,9 @@ func (a *API) handleWatch(rw http.ResponseWriter, r *http.Request) {
ctx = a.wsWatcher.Watch(ctx, logger, conn)
handler := NewHandler(logger, a.opts...)
// Scan returns nil only when no roots are subscribed; once any
// root lands it returns either a delta or a heartbeat message.
// Scan returns nil once the initial state has been sent and no
// roots are subscribed; otherwise it returns a delta or a
// heartbeat message.
scanAndSend := func() {
msg := handler.Scan(ctx)
if msg == nil {
@@ -114,11 +115,7 @@ func (a *API) handleWatch(rw http.ResponseWriter, r *http.Request) {
defer unsubscribe()
// Load any paths that are already tracked for this chat.
existingPaths := a.pathStore.GetPaths(watchChatID)
if len(existingPaths) > 0 {
handler.Subscribe(existingPaths)
handler.RequestScan()
}
handler.Subscribe(a.pathStore.GetPaths(watchChatID))
go func() {
for {
@@ -134,7 +131,9 @@ func (a *API) handleWatch(rw http.ResponseWriter, r *http.Request) {
}()
}
// Start the main run loop in a goroutine.
// The initial scan is sent even with no repos, so the client
// replaces any state left from an earlier connection.
handler.RequestScan()
go handler.RunLoop(ctx, scanAndSend)
// Read client messages.
@@ -151,6 +150,12 @@ func (a *API) handleWatch(rw http.ResponseWriter, r *http.Request) {
switch msg.Type {
case codersdk.WorkspaceAgentGitClientMessageTypeRefresh:
// Re-resolve the chat's paths, as a new connection
// would, so repos created or recreated after their
// paths were recorded are picked up.
if hasWatchChatID && a.pathStore != nil {
handler.Subscribe(a.pathStore.GetPaths(watchChatID))
}
handler.RequestScan()
default:
if err := stream.Send(codersdk.WorkspaceAgentGitServerMessage{