Merged PRs cannot reopen, so their diff-status rows do not need the
two-minute TTL used for open and closed PRs. Use a one-hour TTL after
successful diff-status refreshes of merged PRs while retaining periodic
metadata updates.
Workspace git reports still set `stale_at` to the past so merged
diff-status rows remain eligible for the next worker tick.
Refs CODAGT-1543
When a workspace agent requests external auth, it can send a `chat_id`
(from `CODER_CHAT_ID`) so the current git branch is linked to that chat.
`gitsync.Worker.MarkStale` trusted that ID and never checked that the
chat belongs to the agent's workspace. As a result, any workspace agent
could set the git branch, origin, and PR shown on another user's chat,
and the refresh worker would then fetch PR status with that chat owner's
git token.
`MarkStale` now ignores the request and logs a warning unless both the
requested chat and the root chat that receives the ref are bound to the
calling agent's workspace. Subagent chats are created with their
parent's `workspace_id` (`coderd/x/chatd/subagent.go`), so their
legitimate updates still reach the root chat. The root is checked too
because rebinding a chat's workspace does not rebind its existing
subagent chats. Both external-auth handlers in
`coderd/workspaceagents.go` pass the chat ID through `MarkStale`, so
this single check covers both.
Tests:
- `TestWorker_MarkStale_WithChatID` is now table-driven. A chat on the
same workspace is updated. A chat on another workspace, a chat with no
workspace, and a missing chat get no update and no event.
- `TestWorker_MarkStale_SubagentChatID_UsesRootChat` binds the chats to
real workspaces and adds two calls that must not reach the root: one
from another workspace using the child's ID, and one from the old
workspace through a child after the root is rebound to a new workspace.
- `TestWorker_MarkStale_StripsOriginCredentials` binds its chat to the
caller's workspace, since that test relied on the missing check.
Refs CODAGT-1420, SEC-856. Affects v2.32.0 onward; backports are needed
for every supported release line from 2.32.
<details>
<summary>Investigation notes</summary>
- Source of the chat ID: `agent/agentproc/process.go` sets
`CODER_CHAT_ID` in the process environment, and `cli/gitaskpass.go`
sends it as `chat_id`. Anyone with access to the workspace can set this
value.
- The path without a chat ID already filtered by workspace
(`GetChatsByWorkspaceIDs`); only the chat-ID path skipped the check.
- Open question from the issue (do child chats inherit `workspace_id`?):
yes, `CreateChatWithID` in `subagent.go` sets `WorkspaceID:
parent.WorkspaceID`.
- Edge case (from review): `UpdateChatWorkspaceBinding` rebinds only the
chat it targets, so a child can stay bound to the old workspace after
its root is rebound. Checking only the requested chat let the old
workspace write to the rebound root, so the root's workspace is checked
too.
- I did not add a second rejection in the handlers (optional item 3 in
the issue). `MarkStale` is the only consumer of the chat ID, and
rejecting there would change the external-auth response for git
operations.
</details>
> 🤖 Generated by Coder Agents on behalf of @deansheather.
Removes `Worker.RefreshChat` and the four `TestRefreshChat_*` tests that
only exercised it. `RefreshChat` has had no production caller since
#23901 stopped resolving diff statuses inline on `GetChat`. The worker's
periodic tick is the only refresh path.
`TestWorker_RefreshDoesNotReorderPrimary` used `RefreshChat` to refresh
one of two refs. It now keeps the newer ref fresh (`StaleAt` one hour
ahead) and runs one worker tick, so it checks the same ordering rule
through the production path.
**Why removal is safe:** `git grep '\.RefreshChat('` finds no caller.
Each removed assertion either checked `RefreshChat` itself or is still
caught by a remaining test. I mutated the production line behind each
shared assertion with `go test -overlay`:
| Removed test and assertion | Mutant | Remaining tests that fail |
|---|---|---|
| `TestRefreshChat_Success`: the upsert uses the chat's ID |
`Refresher.refreshOne` upserts a random chat ID |
`TestRefresher_WithPRURL`, `TestWorker`,
`TestWorker_UpsertError_ContinuesNextRow`,
`TestWorker_RefreshDoesNotReorderPrimary` |
| `TestRefreshChat_NoPR`: a branch without a PR is not an error |
`refreshOne` returns an error when there is no PR |
`TestRefresher_BranchNoPRYet` and the three `TestWorker_NoPR_*` tests |
| `TestRefreshChat_RefreshError`: the "no provider" error |
`Refresher.Refresh` changes the "no provider" message |
`TestRefresher_NoProviderForOrigin` |
The other assertions (the returned row, the `upsert chat diff status`
error wrap, and the publish call inside `RefreshChat`) checked only the
deleted method. For the rewritten test, a mutant that sets `updated_at`
in `UpsertChatDiffStatus` fails both the old and the new version. A
mutant that sets `updated_at` in `AcquireStaleChatDiffStatuses` fails
only the new version, because the old version never ran a tick.
**Review focus:** the fixture change in
`TestWorker_RefreshDoesNotReorderPrimary`. #29997 changes one line in
`TestRefreshChat_RefreshError`, so whichever PR lands second drops that
test.
Validation:
- `go test ./coderd/x/gitsync/ -count=1` passes, and `-race -count=5`
passes.
- `golangci-lint run ./coderd/x/gitsync/...` reports 0 issues, and the
pre-commit hook passed.
> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
Stack context: two-layer stack tightening Go lint gates. This bottom
layer fixes the lint exclusion; the layer above adds new rules.
Why: a `.git` path exclusion in the golangci config was hiding Go files,
masking 70 findings. This fixes the exclusion, fixes the findings
(`agent/agentgit` now runs git through `agentexec.Execer`), and adds a
`make lint/go` check that fails when an exclusion hides Go files. `make
lint/go` now waits for a concurrent golangci-lint run instead of
failing. The exhaustruct exclusion rule for `scripts/*` had the same
problem: as a regex it also matched `agent/agentscripts` and
`coderd/agentapi/scripts.go`, so it is now `^scripts/`.
Validation: full-tree lint reports 0 issues; the new check fails on the
old entry and passes on the new one.
> Xum acted for Mike to open and update this PR.
Part 2 of 6. Depends on #29081.
The API now exposes every ref a chat tracks. All API changes are
additive.
- `Chat.diff_statuses` lists every ref on the chat GET and in chat lists
(including child chats). The order is stable: refs are listed by first
report, so the list does not change order when a ref gets a new git
report.
- `Chat.diff_status` is the primary: the ref with the most recent git
report. It is the same rule as before. Use it to find the primary, not
the list position.
- `ChatDiffStatus` gains `remote_origin` and `git_branch`.
- `diff_status_change` watch events carry `changed_diff_status` (`{ref,
status}`) naming the ref that changed. If that ref's row is gone,
`status` contains only `chat_id`.
- `GET /chats/{chat}/diff` accepts optional `origin` and `branch` query
parameters. Set both or omit both (otherwise 400). A selector that
matches no stored ref returns 404. Without a selector the endpoint
returns the primary, as before. The Go SDK adds `WithChatDiffStatusRef`
for this.
- A git report without a chat ID (for example, from a terminal or an
agent older than v2.32) now refreshes only the chats that already track
that ref. It does not add the ref to other chats. Such a report can no
longer give a chat its first ref.
Generated by Coder Agents.
Part 1 of 6.
`chat_diff_statuses` had one row per chat, so a chat could only track
one PR, and switching branches overwrote the old branch's PR data. The
primary key is now `(chat_id, git_remote_origin, git_branch)`, so each
ref the agent reports gets its own row. The API still returns a single
`diff_status`: the first row of the chat's statuses, ordered by
`updated_at`, newest report first. The primary ref changes only when the
agent reports a ref: refreshes, claims, backoffs and URL writes do not
advance `updated_at`, so they cannot reorder the primary.
The gitsync worker now claims, backs off and clears rows by the full
key, not the whole chat. When the diff GET discovers a PR URL, it
updates the existing ref row and no longer inserts one. Telemetry picks
one row per chat.
**NOTE**: Migration `000606` swaps the primary key under an ACCESS
EXCLUSIVE lock. The table is small. Existing rows already fit the new
key, so no data is rewritten. The down migration keeps only the primary
row per chat. Stop old coderd instances before migrating: their `ON
CONFLICT (chat_id)` upserts fail once the old key is gone.
Generated by Coder Agents.
- Adds chat-related dbgen generators covering defaults, overrides, and message field mapping.
- Replaces raw single-row chat, message, provider, and model-config setup in tests with dbgen helpers.
- Simplifies chat seed helpers after moving fixture setup into dbgen.
> Generated with [Coder Agents](https://coder.com/agents).
GetChats now returns only root chats (parent_chat_id IS NULL).
A new GetChildChatsByParentIDs query fetches children for visible
roots and embeds them in each parent's Children field. The
singular getChat endpoint does the same.
Archive invariant is one-way: parent archived implies child
archived. Parent archive/unarchive cascades via root_chat_id.
Individual child archive is permitted; child unarchive while the
parent is archived is rejected atomically (row lock on child,
re-read parent inside the transaction). Embedded children are
filtered by the caller's archive state so individually-archived
children stay hidden from active-parent views.
Gitsync MarkStale uses GetChatsByWorkspaceIDs directly;
MarkStaleParams.OwnerID removed (dead after the switch).
Frontend: buildChatTree reads from the embedded children field,
WebSocket handlers route child events into the parent's children
array, and archiving a child strips it from the parent cache.
Add a `chat_client_type` enum (`ui` | `api`) and `client_type` column to
the `chats` table. The column defaults to `api` for new rows so API
callers don't need to set it explicitly. Existing rows are backfilled to
`ui`.
The field flows through `CreateChatRequest`, `chatd.CreateOptions`,
`InsertChat`, and is returned in the `Chat` response via `db2sdk`.
<details>
<summary>Implementation notes (Coder Agents generated)</summary>
### Changes
**Database migration (000469)**
- New enum `chat_client_type` with values `ui`, `api`.
- New `client_type` column, `NOT NULL DEFAULT 'api'`.
- Backfill: `UPDATE chats SET client_type = 'ui'`.
**SQL query** — `InsertChat` now includes `client_type`.
**SDK** — `ChatClientType` type added; `ClientType` field added to both
`CreateChatRequest` (optional, defaults server-side to `api`) and `Chat`
response.
**Handler** — `postChats` maps the request field (defaulting to `api`)
and passes it through `chatd.CreateOptions`.
**Sub-agent** — Child chats inherit their parent's `client_type`.
**db2sdk** — Maps the database value to the SDK type.
### Decision log
- Default is `api` (not `ui`) so existing API integrations get the
correct value without code changes.
- Backfill sets existing rows to `ui` per requirement.
- Child chats inherit `client_type` from parent rather than defaulting.
</details>
Fixes https://github.com/coder/internal/issues/1436
* Adds organization_id to chats with backfill (workspace org → user org membership → default org)
* No support yet for ACLs (follow-up issue)
- Cross-org workspace binding rejected (both in `CreateChatRequest` and in `create_workspace` tool
- Adds `OrganizationAutocomplete` to `AgentCreateForm`
- Docs updated with `organization_id` in chats-api.md
> 🤖 Written by a Coder Agent. Reviewed by many humans and many agents.
---------
Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
Previously, `CreateChat` inserted the `chats` row with the DB default
status (`waiting`), then updated it to `pending` in the same transaction
via `setChatPendingWithStore`. This wasted two extra queries per chat
creation (`GetChatByID` + `UpdateChatStatus`) and rewrote the same row
immediately after inserting it.
Now `CreateChat` passes the status directly to `InsertChat`, so the row
is written once in its final create-time state. The
`setChatPendingWithStore` helper is removed entirely. `InsertChat` now
requires an explicit `status` parameter at all callsites instead of
relying on a DB column default.
## Motivation
On an experimental branch we're trialing firing all chatd notifications
from plpgsql triggers. The old two-step insert made that awkward: in an
`AFTER INSERT` trigger, `NEW` only contained the insert-time row
(`waiting`), not the final committed state (`pending`). To emit the
correct event payload the trigger had to be deferred and re-read the row
from `chats` at commit time.
With this change, `NEW` already contains the correct row to publish — no
deferred trigger, no extra `SELECT`, simpler and cheaper trigger logic.
That said, this seems like a worthwhile change regardless of the trigger
experiment: writing the final row state once removes unnecessary DB work
on every chat creation and makes the create path easier to reason about.
## Problem
Subagent chats were receiving git context (branch, remote origin, PR
status) from their parent or sibling chats' git operations. When a git
operation triggers external auth, the workspace agent sends `chat_id`
identifying which chat initiated it — but this was broken at two levels:
1. **Agent side:** `CODER_CHAT_ID` was never injected into process
environments. `chatd` sets `Coder-Chat-Id` HTTP headers and the
agent extracts them for process isolation, but never propagated
`CODER_CHAT_ID` to `cmd.Env`. So `gitaskpass` always sent an empty
`chat_id`.
2. **Server side:** `workspaceAgentsExternalAuth` ignored the `chat_id`
query param. `MarkStale` broadcast git context to **all** chats on
the workspace via `filterChatsByWorkspaceID`.
## Fix
- Inject `CODER_CHAT_ID` into `cmd.Env` in `agentproc` when the chat
ID is known, so `gitaskpass` can read and forward it.
- Read `chat_id` from query params in `workspaceAgentsExternalAuth`
and thread it through `chatGitRef`.
- Refactor `MarkStale` to accept a `MarkStaleParams` struct. When
`ChatID` is provided, target only that specific chat. When empty
(legacy agents, non-chat git operations), fall back to the existing
workspace-wide broadcast.
- Extract `markStaleSingle` helper to deduplicate the upsert+publish
logic.
<details><summary>Investigation notes</summary>
### Data flow before fix
```
chatd → sets Coder-Chat-Id header on agent conn
agent → extracts chatID, stores on process struct
agent → does NOT set CODER_CHAT_ID in cmd.Env ← gap 1
gitaskpass → reads CODER_CHAT_ID (always empty), sends chat_id=""
server handler → ignores chat_id query param ← gap 2
MarkStale → broadcasts to ALL workspace chats
```
### Data flow after fix
```
chatd → sets Coder-Chat-Id header on agent conn
agent → extracts chatID, stores on process struct
agent → sets CODER_CHAT_ID in cmd.Env
gitaskpass → reads CODER_CHAT_ID, sends chat_id=<uuid>
server handler → reads chat_id, passes to MarkStale
MarkStale → targets only that specific chat
```
</details>
## Summary
Adds read/unread tracking for chats so users can see which agent
conversations have new assistant messages they haven't viewed.
## Backend Changes
- Adds `last_read_message_id` column to the `chats` table (migration
000439).
- Computes `has_unread` as a virtual column in `GetChatsByOwnerID` using
an `EXISTS` subquery checking for assistant messages beyond the read
cursor.
- Exposes `has_unread` on the `codersdk.Chat` struct and auto-generated
TypeScript types.
- Updates `last_read_message_id` on stream connect/disconnect in
`streamChat`, avoiding per-message API calls during active streaming.
- Uses `context.WithoutCancel` for the deferred disconnect write so the
DB update succeeds even after the client disconnects.
## Frontend Changes
- Bold title (`font-semibold`) for unread chats in the sidebar.
- Small blue dot indicator next to the relative timestamp.
- Suppresses unread indicator for the currently active chat via
`isActive` from NavLink.
## Design Decisions
- Only `assistant` messages count as unread — the user's own messages
don't trigger the indicator.
- No foreign key on `last_read_message_id` since messages can be deleted
(via rollback/truncation) and the column is just a high-water mark.
- Zero API calls during streaming: exactly 2 DB writes per stream
session (connect + disconnect).
- Unread state refreshes on chat list load and window focus. The
`watchChats` WebSocket optimistically marks non-active chats as unread
on `status_change` events, but does not carry a server-computed
`has_unread` field. Navigating to a chat optimistically clears its
unread indicator in the cache.
## Problem
When chatd pushes a branch and then creates a PR (e.g. `git push`
followed by `gh pr create`), the gitsync background worker often picks
up the stale `chat_diff_statuses` row between the two operations. At
that point no PR exists yet, so the worker skips the row. However, the
acquisition SQL locks the row for **5 minutes** (crash-recovery
interval), creating a dead zone where the PR diff is invisible in the UI
until the user manually navigates to the chat.
### Root cause
1. `git push` triggers `GIT_ASKPASS` → coderd external-auth handler →
`MarkStale()` sets `stale_at = now - 1s`
2. Background worker acquires the row within ~10s, atomically bumps
`stale_at = NOW() + 5 min` (crash-recovery lock)
3. Worker calls `ResolveBranchPullRequest` → no PR exists yet → returns
`nil` → worker skips with `continue`
4. `gh pr create` completes moments later, but uses its own auth (not
`GIT_ASKPASS`), so no second `MarkStale` fires
5. Row is locked for 5 minutes before the worker can retry
Loading the chat works immediately because `GET /chats/{chat}` calls
`resolveChatDiffStatus` synchronously, which discovers the PR inline.
## Fix
When `ResolveBranchPullRequest` returns nil (no PR yet) **and** the row
was recently marked stale (within 2 minutes), apply a short 15-second
backoff via `BackoffChatDiffStatus` instead of letting the 5-minute
acquisition lock stand. Outside the retry window, the worker skips the
row as before — no indefinite fast-polling for branches that never
receive a PR.
To make the "recently marked stale" check work, `updated_at` is no
longer overwritten by the acquisition and backoff SQL queries. This
preserves it as a reliable "last externally changed" timestamp (set by
`MarkStale` or a successful refresh).
### Behavior summary
| Scenario | `updated_at` age | Backoff | Effective retry |
|---|---|---|---|
| Fresh push, no PR yet | < 2 min | 15s (`NoPRBackoff`) | ~15s |
| Old row, no PR | ≥ 2 min | None (skip) | ~5 min (acquisition lock) |
| Error (any age) | Any | 120s (`DiffStatusTTL`) | ~120s |
| Success (any age) | Any | 120s (`DiffStatusTTL`) | ~120s |
## Changes
- **`coderd/database/queries/chats.sql`** — Remove `updated_at = NOW()`
from `AcquireStaleChatDiffStatuses` and `BackoffChatDiffStatus`
- **`coderd/database/queries.sql.go`** — Regenerated
- **`coderd/x/gitsync/worker.go`** — Add `NoPRBackoff` (15s) and
`NoPRRetryWindow` (2 min) constants; apply short backoff only within the
retry window
- **`coderd/x/gitsync/worker_test.go`** — Add
`TestWorker_NoPR_RecentMarkStale_BacksOffShort` and
`TestWorker_NoPR_OldRow_Skips`
- Moves `coderd/chatd/`, `coderd/gitsync/`, `enterprise/coderd/chatd/`
under `x/` parent directories to signal instability
- Adds `Experimental:` glue code comments in `coderd/coderd.go`
> 🤖 This PR was created with the help of Coder Agents, and was
reviewed by my human. 🧑💻