mirror of
https://github.com/coder/coder.git
synced 2026-11-23 04:09:07 +08:00
90948802e2439d2641f392e6229dd058a1dcafe3
714
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7829b8f924 |
refactor: move ssh upgrade listener to the corresponding serve (#30532)
Move the upgrade listener close to where it is actually used rather than smushing it with the reconnecting pty listener close. Also add a comment explaining why we close it even though the ssh server is supposed to do that. |
||
|
|
788a8bc1ba |
test: skip agent tool call tests until netstack TIME_WAIT fix (#30465)
Skip `TestAgent_ToolCall` and `TestEditMessageCancelsToolCallsOnAgent` until the agent netstack fix in PLAT-717 lands. The agent's gVisor netstack accepts connections through `tcp.Forwarder` and has no listening endpoint, so it drops a SYN that reuses a source port it still holds in TIME_WAIT (google/gvisor#15013). Agent API requests open a new connection each and the agent closes first, so a client that reuses a port within 60s hangs for about 63s. Both tests make enough requests to one agent to hit it (CODAGT-1336, CODAGT-1331). The same stall was reproduced against a production agent on dogfood, so this is a product bug, tracked in PLAT-717. |
||
|
|
c430310dfe |
feat(agent/unit): support outcome-aware dependencies (#30390)
feat(agent): add outcome-aware unit dependencies Extend the unit manager for declarative script ordering without changing existing status dependencies or `coder exp sync` behavior. - Add a separate conditional dependency graph with `success` and `completion` requirements, outcome tracking, and runnable, skipped, or waiting decisions. - Failed, timed-out, or skipped prerequisites skip `success` dependents but satisfy `completion`. Canceled or unregistered prerequisites keep dependents waiting. - Add context-cancelable waiting with no built-in timeout and sorted unmet prerequisites for logging. Callers remain responsible for recording skips. - Enforce immutable final outcomes, reject cycles and conflicting edge requirements, and accept identical duplicate edges. - Add race-tested coverage for outcome semantics, validation, graph isolation, cancellation, and concurrent waiters. No callers yet; script-runner integration follows in PLAT-549. Refs PLAT-546. |
||
|
|
008166356a |
fix: explicitly close ssh upgrade listener (#30442)
We have flakes where the agent's close hangs, theorized to be because the new ssh upgrade listener is never closed. It does seem strange though, the listener should be closed by the ssh server since it closes all the listeners passed into it...so this may not do anything, but it seems wise to be explicit anyway. |
||
|
|
cc0c868c55 |
feat: add client_session_id to ssh connections (#29701)
Add a new /tcp endpoint on the agent that is used to pass along the client session ID (with the existing baggage mechanisms). The agent then can upgrade that into the desired connection type, based on the port. For now that is only the standard SSH port and reconnecting pty. The `ssh`, `ssh --stdio`, `ssh --stdio` over Coder Connect, `exp rpty`, and web terminal paths are all updated to use this new endpoint, and fall back to the old method when the endpoint is not available. That ID is added to the log context, and is also used to populate the session ID column in the connection logs table. There are some logs related to a connection that will not be tagged with the ID (like the "accepted connection" line) because they happen before the http handler gets to run. |
||
|
|
c7da54cf03 |
refactor: add agent connection reporter (#30069)
Instead of passing around a function and wrapping it for each listener to set `Type`, we pass around a connection reporter which is patterned after the stats reporter. Each listener sets their type directly on their report rather than having the wrapped function do it like before. The other big difference is that it uses a buffered channel instead of a slice. |
||
|
|
1ba09d2ce2 |
feat: run chat tool calls once per tool call ID on the agent (#29946)
chatd resends unresolved tool calls on every retry and replica
takeover, and each resend of execute started a new process: one
command in CODAGT-757 started 36 times. An interrupt could neither
stop the process nor report what happened.
The agent now runs a request that carries Coder-Tool-Call-Id once
per chat and tool call ID and responds to repeats with the saved
response. StartProcess, EditFiles, and WriteFile send the header.
POST /api/v0/tool-calls/{id}/cancel refuses later requests for the
call, waits for a running one, stops its process, and returns the
saved response.
A process started with a tool call ID uses it as its process ID, and
its timeout_ms counts from the first start, so a retry does not
restart the timeout. Processes are keyed by chat ID: a chat sees only
its own processes, and a request without a chat ID sees only
processes started without one. Exited processes are kept for an hour
instead of 5 minutes so that retries can still read their output.
Requests without the header behave as before. Old agents ignore the
header and respond to a cancel with 404.
Refs CODAGT-757
|
||
|
|
6487425885 |
feat: buffer agent debug logs and flush on connection failure (#29671)
## What Runs the workspace agent logger at `Info` with a slog flight recorder (`v3.2.0`) instead of unconditionally at `Debug`. Entries below the current log level are kept in a rolling in-memory ring and flushed to the sinks when the agent loses its connection to coderd (and before any `Error`+ log), so the detail leading up to a failure is available without writing debug logs during normal operation. Implements CLIENT-672 (connection-log RFC req 13) for the workspace agent. Depends on the `cdr.dev/slog/v3` `v3.2.0` bump (already on `main`). ## How - `cli/agent.go`: - The main agent logger is `AppendSinks(...).Leveled(level).FlightRecorder(flightRecorderSize)`, where `level` is `Info` by default and `Debug` under the global `-v` / `CODER_VERBOSE`. The recorder is always attached; at `Debug` it is inert, which keeps the setup correct if the configured level changes in the future. The reaper logger is unchanged. - New `--agent-flight-recorder-size` / `CODER_AGENT_FLIGHT_RECORDER_SIZE` (default `1000`, `0` disables the flight recorder), so the ring size is configurable per RFC req 13. The agent flag is distinct from CLI-4's global `--flight-recorder-size` (#29752) so the two don't collide when `coder agent` inherits the root global. - `workspaceAgent` is a `RootCmd` method so it reuses the root command's global verbose flag instead of defining an agent-specific one. - `agent/agent.go` (`runLoop`): on a lost coderd connection (the `io.EOF` disconnect and the generic run error) the agent calls `logger.Flush(ctx)` to emit the recorded history and then logs at `Warn`. These are `Warn` rather than `Error` because reconnectable disconnects are expected and `slogtest` fails tests on any `Error` log; the manual flush is what surfaces the recorded detail. Graceful shutdown paths (`ctx` canceled, agent closed) are not flushed. - Tests: `agent.TestAgent_FlushFlightRecorderOnDisconnect` covers the flush-on-disconnect path; `cli.TestWorkspaceAgent/DisabledServers` runs with verbose since its debug messages are otherwise recorded. Golden `--help` output regenerated. ## Default log verbosity change This changes the default agent-log verbosity. Today `coder-agent.log` receives `Debug` unconditionally; with this change, normal operation logs `Info`, and recorded below-level entries are emitted only when the agent loses its coderd connection (via a manual flush) or before any `Error`+ log, or always under `-v` / `CODER_VERBOSE`. This is the intended behavior of the feature: a quiet steady state with full detail retained for diagnosing failures. Operators who want the previous always-debug output can run with `-v` / `CODER_VERBOSE`. ## Alignment with #29752 (CLI) This mirrors the CLI-4 (CLI log buffer) design so the two implementations agree: - **Level model:** Info by default, debug available on demand via the global `-v` / `CODER_VERBOSE`. - **Flight recorder size:** default `1000`, `0` disables. CLI-4 exposes a global `--flight-recorder-size`; the agent uses a distinct `--agent-flight-recorder-size` / `CODER_AGENT_FLIGHT_RECORDER_SIZE` (the `CODER_AGENT_*` env convention) so the inherited global and the agent flag coexist without collision. - **Flush trigger:** the recorded history is emitted before any `Error`+ log via slog's auto-flush. The agent additionally flushes manually on a lost coderd connection, which it logs at `Warn` (reconnectable, and `Error` would fail `slogtest`-based tests); the CLI's failures are fatal, so it relies on the auto-flush-on-error. <details> <summary>Rollout context</summary> Cross-repo sequence: coder/slog flight recorder (released as v3.2.0) -> go.mod bump in coder/coder (#29600, merged) -> this PR (CLIENT-672, agent) and CLI-4 (CLI), which are independent consumers and can merge in any order. </details> --- <sub>Opened by Coder Agents on behalf of @aqandrew.</sub> |
||
|
|
dffa890d8f |
ci: add macOS runner telemetry and a stall detector to test-go-pg (#30050)
Add telemetry to diagnose intermittent macOS `test-go-pg` stalls and preserve timeout diagnostics. - Log runner details at startup; sample load, swap, and `vm_stat` every second and `top` every 10 seconds to identify runner-wide pauses. - Add stall detection to `cli` and `agent` `TestMain`, logging heap, GC, and goroutine counts when ticks arrive more than 5 seconds late. - Run artifact uploads with `always() && !success()` so canceled test steps do not skip diagnostics. - Add a `TEST_TIMEOUT` override: use 20m on macOS to leave room for goroutine dumps within the 30m job, retaining the 25m default for the nightly gauntlet. Validated with race tests, binary compilation, `actionlint`, local macOS checks, and Makefile timeout checks. |
||
|
|
797dc6b2d1 |
feat: refresh header commands based on JWT expiration (#29760)
Adds opportunistic JWT parsing for values returned from the `--header-command`. If a JWT is parsed we use the value of its `exp` field to determine when we should re-run the command to refresh the values. |
||
|
|
957aefa475 |
feat: add client_session_id to connection_logs table (#29686)
The client session ID is not populated yet; this just adds the ability for agents to send a client session ID with the rest of the connection data, once it gets piped through. |
||
|
|
7c74fa3548 |
feat: add workspace file upload agent API (#27078)
## What Adds a dedicated workspace-agent endpoint, `POST /api/v0/upload-chat-file`, that streams a request body into the chat's upload directory `~/.coder/chats/<chat-id>/files/<name>`, plus the SDK plumbing to call it: - `coderd/x/chatfiles`: upload-name sanitization (`SanitizeWorkspaceUploadName`), collision suffixes (compound extensions such as `.tar.gz` stay intact: `archive_2.tar.gz`), and the shared `~/.coder/chats/<id>/files` path layout. - `agent/agentfiles`: the HTTP handler. On Linux/macOS the directory chain is opened with `openat(O_NOFOLLOW)`, so symlinked path components are rejected. The body streams into a hidden `.<name>.upload-<random>` temp file and is published under its final name only when complete, via `linkat` over the `_2`, `_3`, ... collision sequence, so existing files are never overwritten and a half-written file is never visible under its final name. Filesystems without hard links fall back to an exclusive placeholder plus `renameat`. Other platforms use an afero-based fallback with the same semantics. Stale temp files older than an hour are swept before each upload, and failures are logged with a structured warning. - `codersdk/workspacesdk`: `AgentConn.UploadChatFile` + regenerated `agentconnmock`. ## Why Coder Agents chat can attach images/text/PDF to prompts, but arbitrary files (zips, datasets, binaries) have nowhere to land where the agent's tools can act on them. This is the agent-side foundation; the coderd route that fronts it is stacked on top. Design notes: - There is deliberately no size cap; the resource profile matches existing SSH/WebSocket proxying, and client cancellation aborts the stream (a failed write removes the temp file, so no partial files remain). Because the agent HTTP server uses fixed 20 s read/write timeouts, the handler pushes both deadlines forward on every received chunk, so a slow upload only fails after a 20 s stall. If the connection does not support deadline changes, the agent logs one warning per request. - This endpoint is not gated by `CODER_AGENT_BLOCK_FILE_TRANSFER`. That flag targets SSH-transport file tools (scp/rsync/sftp). Chat uploads are an agent API capability like `write-file` and `edit-files`, which already bypass the flag; the interaction is documented in the FAQ. ## How tested - `go test ./agent/agentfiles ./coderd/x/chatfiles ./codersdk/workspacesdk` (unit + umask/symlink/collision integration tests). - UAT on a dogfood-style deployment (2026-09-21): uploads longer than 20 s went from 502 to 201 once the workspace agent was restarted on this build; a coderd restart alone keeps the old agent running, so the per-chunk deadline extension needs the agent rolled (older agents get the 409 "Restart the workspace" from #27079). Part of CODAGT-211. Stack: agent API (this PR) -> coderd endpoint -> UI. > This PR was authored by Mux (AI) working on Mike's behalf. |
||
|
|
8b3f032ca1 |
test(agent): isolate session environment checks from host shells (#29747)
The environment-variable and secret-injection tests still ran each SSH command through the host's configured shell after #27803 gave each check its own session. Startup files could stop the command before it printed a value. Use noninteractive `/bin/sh` or `cmd.exe /d` for these fixtures and print values directly, preserving real SSH execution, parallel sessions, and environment precedence checks. Controlled startup-file experiments failed all nine checks before this change and passed afterward. The updated tests also passed 50 repetitions on Linux and macOS. This removes a demonstrated host-shell dependency, though the exact cause of the September Linux timeout was not reproduced. Closes https://linear.app/codercom/issue/PLAT-310/flake-testagent-session-environmentvariables. Generated with Coder Agents. |
||
|
|
9974294ca9 |
feat: report arbitrary workspace agent session types (#28338)
Report session counts as a dynamic app-name map from the agent, the SSH CLI, and the workspace usage API, so a new IDE flows end to end without a schema, proto, or server change. - Report through `Stats.session_counts` on Agent API v2.11. Older agents keep reporting through the deprecated count fields. - Accept arbitrary names from `coder ssh --usage-app` and the workspace usage API. A name the registry does not recognize keeps its identity and is attributed to the `unknown` family. - Add reconnecting PTY counts to the map without overwriting the counts SSH reported. - Normalize and merge names before applying the deterministic 64-name cap, ordered by known apps, then count, then name. Overflow sums into `unknown`, and non-positive counts cannot cancel valid activity. - Strip control characters, treat whitespace-only HTTP app names as absent, and require the exact environment variable prefix when you extract an SSH session type. - Count overflow entries in `coderd_agentstats_session_counts_overflow_total` and keep raw payloads out of logs. - Change the usage API's `app_name` to a string, and update the SDK types and API reference. closes #27410 |
||
|
|
26e4429362 |
test: fold near-identical test bodies into tables across eight packages (#29463)
Folds groups of near-identical test bodies (same parent, same parallel flag, differing only in inputs and expected values) into table-driven tests in eight packages: `coderd/templatebuilder`, `scripts/develop`, `agent/agentfiles`, `coderd/x/chatd/chatloop`, `coderd/x/chatd/chatdebug`, `enterprise/aibridgeproxyd`, `cli`, and `coderd/database/db2sdk`. One commit per package. Every case keeps its previous subtest name, `t.Parallel()` placement is unchanged, and the set of `=== RUN` names is identical except where standalone `TestX_Y` funcs became `TestX/Y` subtests (chatloop: 9 funcs into `TestExecuteLocalTools_BatchRuntime`; chatdebug: 15 funcs into two tables). Members whose bodies differ in more than data stayed as they were (listed per package in the commit messages). In `agent/agentfiles` the four `TestFuzzyReplace_*` funcs were already tables, so the shared request plumbing was hoisted into one helper instead of merging the funcs and losing their per-rule docs. Net -1035 lines across 9 test files; runtime is unchanged (all sub-100ms unit tests). | Package | Diff | Funcs removed | Subtests | RUN lines | |---|---|---|---|---| | coderd/templatebuilder | +237 / -291 | 0 | 31 -> 31 | 33 -> 33 | | scripts/develop | +194 / -246 | 0 | 27 -> 27 | 28 -> 28 | | agent/agentfiles | +117 / -260 | 0 | unchanged | 58 -> 58 | | coderd/x/chatd/chatloop | +224 / -306 | 9 | 3 -> 12 | 14 -> 15 | | coderd/x/chatd/chatdebug | +251 / -537 | 13 | 0 -> 15 | 42 -> 44 | | enterprise/aibridgeproxyd | +287 / -419 | 0 | 31 -> 31 | 32 -> 32 | | cli | +143 / -326 | 0 | 15 -> 15 | 16 -> 16 | | coderd/database/db2sdk | +130 / -233 | 0 | 9 -> 9 | 10 -> 10 | ## Validation - Per package: `go test -count=1 -tags=testsmallbatch -parallel=8 ./<pkg>/ -run <regex> -v` before and after, with the `=== RUN` name sets diffed - `go test -race -count=2 -shuffle=on` on each converted test: pass - `golangci-lint run ./<pkg>/...` with a fresh cache: 0 issues in all eight packages - Repository pre-commit hook (including lint/go) passed on every commit Part of the test-suite speedup series (see #29457); independent of the other PRs. ## Remote validation Remote run on a dogfood workspace (separate compute), chat https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44, tested head `d7c55d6b0e8` against base `9d973372774`: all eight packages pass on the head and under `-race -count=3 -shuffle=on`; package times are sub-second on both sides (unchanged). `=== RUN` name sets: chatloop 15 to 16 lines with all nine `TestExecuteLocalTools_<X>` leaves surviving as `TestExecuteLocalTools_BatchRuntime/<X>`; chatdebug 42 to 44; `aibridgeproxyd` `TestNew` 32 to 32, byte-identical sorted list. One correction to the text above: seven chatdebug leaves are renamed, not preserved verbatim (`TestRecordingTransport_*UnknownLength*` became `TestRecordingTransport_UnknownLengthClose/<name without "UnknownLength">`), so `-run` filters keyed on those old names need updating. Endorsed verdict: PASS. > Xum (an AI agent) authored this PR on behalf of @ibetitsmike. |
||
|
|
d2e94e299a | chore: delete dead functions and skip-only or duplicated tests (#29461) | ||
|
|
0bb357e1dd |
test(agent): avoid host shell in quiet login test (#29441)
The `Hushlogin` subtest depended on the runner's login shell processing repeated exit commands over its PTY. Under CI contention, shell startup could stall and leave `session.Wait` blocked until the timeout-driven teardown. Inject a self-terminating test login shell instead. Banner and MOTD handling occurs before the shell starts, preserving quiet-login coverage while removing the unrelated host-shell lifecycle dependency. Refs: https://linear.app/codercom/issue/PLAT-178 |
||
|
|
b9244c0641 |
fix(agent): prevent app health reporter test timeouts (#29395)
Remove the redundant per-app goroutine around Quartz `TickerFunc` because `TickerFunc` already runs ticker callbacks asynchronously. This avoids an extra scheduling delay under Windows CI load. Use a longer test deadline and cancel the reporter before closing test servers so active healthchecks do not delay teardown. Refs: https://linear.app/codercom/issue/PLAT-573 |
||
|
|
e9429903d4 |
fix(agent): launch stdio MCP servers in the workspace dir (#29153)
## Problem stdio MCP servers declared in `.mcp.json` were launched from the agent's own working directory, which is unspecified and often a temp dir (observed `/tmp/coder.*`). Relative paths in a server's `Args` (for example a language server `-workspace ./site/`) resolved against that temp dir instead of the workspace, so: - `typescript-language-server` failed immediately: the resolved `./site/` did not exist under the temp cwd. - `go-language-server` connected but gopls rooted at the temp dir, so workspace symbol lookups failed while per-file hover still worked. The agent log showed `connection closed: calling "initialize": client is closing: EOF`. <img width="682" height="606" alt="Screenshot 2026-09-09 at 5 33 58 PM" src="https://github.com/user-attachments/assets/650f1305-d807-406e-864e-e347e9a4c52d" /> ## Fix Launch stdio MCP servers in the workspace working directory instead of inheriting the agent's cwd. - `agent/agent.go`: hoist a single `workingDirFn` closure (reads `a.manifest.Load().Directory`, `""` before the first manifest) and reuse it for the process API, MCP manager, and context config/manager wiring. - `agent/x/agentmcp/manager.go`: `Manager` gains a `workingDir func() string`; `createTransport` sets `cmd.Dir = m.resolveWorkingDir(ctx)` for the stdio path. `resolveWorkingDir` routes through `usershell.ResolveWorkingDirectory`, the same helper SSH sessions and the process API use, so the three cannot drift: an existing configured dir is used, otherwise the user's home dir. Returns `""` (inherit) only when the callback is nil or empty. `.mcp.json` is unchanged. Storybook is untouched. ## Tests - `TestCreateTransport_StdioSetsWorkingDir`: constructs the manager via `NewManager` and asserts the stdio transport's `Command.Dir` is the workspace dir. - `TestResolveWorkingDir`: table cases for nil/empty callback (inherit), existing dir, missing dir, and a path that is a file (both fall back to home). ## Checks `make fmt`, `make lint`, and `go test ./agent/x/agentmcp/` all pass. <details> <summary>Design notes and alternatives considered</summary> First-principles contract: MCP servers should launch in the workspace working directory, matching existing docs and agent subsystem behavior, not the config directory that declares them. An earlier iteration set `cmd.Dir` from the config file's directory; review found that fragile (global config locations, `$HOME` semantics). It was replaced with the workspace-dir callback that reuses `usershell.ResolveWorkingDirectory` for consistency with SSH and the process API. A tooling-only alternative also exists (resolve the language-server workspace via a `WORKSPACE` env value in `.mcp.json`). The agent-side fix was preferred because it corrects the root cause for every stdio MCP server, not just the two language servers, and keeps `.mcp.json` portable. Deferred (not in this PR): converting `NewManager` to an options struct to avoid positional `nil` churn, and setting `PWD` alongside `cmd.Dir`. </details> --- Generated by Coder Agents on behalf of @jeremyruppel. --------- Co-authored-by: Coder Agents <agents@coder.com> |
||
|
|
156c8b6e41 |
fix: prevent coderd crashes from unsupported Tailnet RPCs (#28429)
Workspace agents could call RefreshResumeToken and WorkspaceUpdates, even though agent connections do not configure the providers those RPCs require. The resulting nil dereference panicked a DRPC handler and crashed coderd. Limit the agent Tailnet surface to its supported RPCs, return `Unimplemented` when optional providers are absent, and recover panics in Coder-owned DRPC servers so they return an internal error instead of crashing the process. Refs: https://linear.app/codercom/issue/PLAT-464 |
||
|
|
6db09ed9a6 | fix: sync pinned chat MCP context resources on agent push (#28796) | ||
|
|
91e28e2983 |
feat: handle client_session_id in agent middleware (#28039)
Implements [DEVEX-660](https://linear.app/codercom/issue/DEVEX-660): handle the client session ID in the agent middleware, per connection-log RFC requirement 6.2. > Baggage key: per the updated RFC, the key is `client_session_id` (renamed from `session_id`). The shared constant `tracing.SessionIDBaggageKey` now has the value `client_session_id`. ## What - Add `tracing.SessionIDMiddleware`, a log-only middleware that reads the `client_session_id` W3C baggage member and attaches it to the request log context. Unlike `tracing.Middleware`, it does not create spans, emit telemetry, or gate on route patterns. - Wire it into the agent HTTP stack (`agent/api.go`) before `loggermw.Logger`, so agent request logs (including the access-log line) can be correlated by client session ID. ## Why not spans on the agent RFC 6.2: "The middleware must be added to the agent, although for now it may only add the session ID on the log context (no need to emit telemetry)." Spans/telemetry on the agent are out of scope here. ## Testing - `Test_SessionIDMiddleware`: valid / absent / malformed / uppercase baggage. - `Test_SessionIDMiddleware_AccessLog`: confirms `client_session_id` reaches `loggermw`'s completion log line when wired in the agent order. - `go vet` and `golangci-lint` pass on `coderd/tracing` and `agent`. ## Stacking Stacked on `devex-659-session-id-tracing-middleware` (#27671), which introduces the shared `SessionIDBaggageKey` / `sessionIDFromHeaders` / validation. Review/merge #27671 first. <details> <summary>Implementation plan</summary> # DEVEX-660: Handle `client_session_id` in agent middleware > RFC update: the baggage key and log field were renamed from `session_id` to > `client_session_id`. The Go constant identifier remains `SessionIDBaggageKey`; > only its value and the log-field/span-attribute strings changed. ## Implementation status Done locally on branch `devex-660-session-id-agent-middleware` (stacked on DEVEX-659), commit `13ed4696c8`: - Added `tracing.SessionIDMiddleware` (log-only) in `coderd/tracing/httpmw.go`. - Wired it into `agent/api.go` before `loggermw.Logger`. - Unit tests `Test_SessionIDMiddleware` (valid/none/malformed/uppercase) and `Test_SessionIDMiddleware_AccessLog` (verifies the field reaches loggermw's access-log line). Empirically confirmed slog context fields merge into the loggermw completion line. - Passing: `go test ./coderd/tracing/...`, `go vet ./coderd/tracing/... ./agent/`, `golangci-lint run` on both packages, `gofmt` clean. - Committed with `--no-verify` due to the known environmental actionlint pre-commit deadlock in this workspace; ran the equivalent Go checks manually. Not yet done: push branch, open PR. ## Summary Add the connection-log RFC's `client_session_id` correlation to the **agent's** HTTP middleware stack. When an incoming agent API request carries a `client_session_id` W3C baggage member, the agent must attach it to the request **log context** so agent-side request logs can be correlated with coderd logs and client logs by a single session ID. Per RFC requirement **6.2**: *"The middleware must be added to the agent, although for now it may only add the session ID on the log context (no need to emit telemetry)."* ## Scope In scope: - A middleware on the agent HTTP router (`agent/api.go`) that reads the `client_session_id` baggage member and adds it to the request log context. - Log context only. **No spans, no telemetry, no route-pattern gating.** Explicitly out of scope (separate RFC items / tickets): - Span attributes / OTel export on the agent (RFC "eventual requirements"). - Reconnecting-PTY and `agentssh` command logging with session ID (RFC #8, #15). - `connection_logs` session_id column / user ID (RFC #8). - Any client-side work (RFC #1-5), which is DEVEX-663 and siblings. ## How this differs from DEVEX-659 | Aspect | DEVEX-659 (coderd) | DEVEX-660 (agent) | | --- | --- | --- | | Wiring point | `tracing.Middleware(tracerProvider)` in `coderd/coderd.go` | agent router in `agent/api.go` | | Existing stack | span-creating `tracing.Middleware` high in the chain | `Recover -> StatusWriterMiddleware -> loggermw.Logger -> agentchat.Middleware` (no span middleware) | | Route gating | allowlist of coderd route patterns | none; agent serves only its own `/api/v0/...` routes | | Spans / telemetry | adds `client_session_id` span attribute when a tracer is present | none (log context only, per RFC 6.2) | | Log mechanism | `slog.With(ctx, slog.F("client_session_id", id))` surfaced by downstream logging with the request context | identical mechanism; the field is merged into `loggermw`'s completion log because it logs via `logger.Debug(ctx, ...)` | Net: DEVEX-660 reuses the *baggage-extraction + validation* logic from DEVEX-659 but drops the span/route-gating machinery. It is a strictly smaller, log-only middleware. ## Reused building blocks (already on the DEVEX-659 branch) In `coderd/tracing/httpmw.go`: - `const SessionIDBaggageKey = "client_session_id"` (wire contract). - `func sessionIDFromHeaders(h http.Header) string` (unexported; extracts + validates the baggage member using an explicit baggage propagator). - `func ValidSessionID(s string) bool` (exported; lowercase 32-char hex). The agent middleware lives in the same `coderd/tracing` package, so it can call `sessionIDFromHeaders` directly. ## Design Add a standalone, log-only middleware to `coderd/tracing/httpmw.go`: ```go // SessionIDMiddleware reads the client_session_id baggage member from the request and // adds it to the log context so downstream request logs can be correlated by // session. Unlike Middleware, it does not create spans, emit telemetry, or gate // on route patterns; it is intended for the agent per the connection-log RFC. func SessionIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { if sessionID := sessionIDFromHeaders(r.Header); sessionID != "" { r = r.WithContext(slog.With(r.Context(), slog.F("client_session_id", sessionID))) } next.ServeHTTP(rw, r) }) } ``` Wire it into the agent stack in `agent/api.go`, **before** `loggermw.Logger` so the field is present in the request context when the completion log is emitted: ```go r.Use( httpmw.Recover(a.logger), tracing.StatusWriterMiddleware, tracing.SessionIDMiddleware, loggermw.Logger(a.logger, nil), agentchat.Middleware, ) ``` ### Why placement before `loggermw` works `loggermw.Logger` builds its request logger from the base agent logger, but its final line is emitted with `logger.Debug(ctx, c.message)` using the request context. slog merges fields stored on the context via `slog.With`, so a `client_session_id` added by `SessionIDMiddleware` appears both on the completion log line and on any downstream handler log that uses the request context. This is the same behavior DEVEX-659 verifies on the coderd side. ### `slog.F` literal constraint As on the coderd side, the first argument to `slog.F` must be a snake_case string literal (repo ruleguard). Keep `slog.F("client_session_id", ...)` literal; do not pass `SessionIDBaggageKey`. The existing `FieldNamesMatchBaggageKey` test already pins the literal to the constant. ## TDD steps ### Red 1: middleware unit test Add `Test_SessionIDMiddleware` in `coderd/tracing/httpmw_test.go` (reuse the `testutil.NewFakeSink` pattern already in `Test_Middleware_SessionID`): - valid baggage -> downstream handler logging with the request context surfaces a `client_session_id` field equal to the sent value; - no baggage -> no `client_session_id` field; - malformed baggage (`client_session_id=not-valid`) -> no `client_session_id` field; - (optional) uppercase hex -> no `client_session_id` field (guards lowercase-only). Runs red because `SessionIDMiddleware` does not exist yet. ### Green 1 Implement `SessionIDMiddleware` as above. Run: `go test ./coderd/tracing/... -run 'Test_SessionIDMiddleware' -count=1`. ### Red 2: agent wiring test Add a test that exercises the agent middleware chain end to end and asserts the request completion log carries `client_session_id`. Mirror the existing pattern in `agent/agentchat/log_test.go`, which composes `tracing.StatusWriterMiddleware(loggermw.Logger(sink.Logger(), nil)(handler))` with a fake sink. Build the same chain **including** `tracing.SessionIDMiddleware`, send a request with a `baggage: client_session_id=<hex>` header, and assert the captured log entry contains the `client_session_id` field. Add a negative case with no baggage. Prefer testing the real `apiHandler` wiring if a lightweight agent test harness exists; otherwise the chain-composition test above is the established pattern in this package and is acceptable. Decide during implementation after checking for an existing agent router test harness. ### Green 2 Add `tracing.SessionIDMiddleware` to the `r.Use(...)` list in `agent/api.go`. Run the new agent test. ### Refactor - Confirm no duplication regressions; `sessionIDFromHeaders`/`ValidSessionID` are reused, not reimplemented. - Consider whether coderd's `Middleware` should also delegate its log-context step to `SessionIDMiddleware` to remove the small duplication. Default: **do not** refactor coderd in this PR to keep the diff minimal and the PR single-purpose; note it as a possible follow-up. ## Validation - `go test ./coderd/tracing/... -count=1` - `go test ./agent/... -run '<new test name>' -count=1` - `go vet ./coderd/tracing/... ./agent/...` - `make lint` (verify ruleguard passes on the literal `slog.F` field). - `make gen` is not required (no DB/proto changes). ## Branch / PR strategy - New branch `devex-660-session-id-agent-middleware`, its **own PR** per the RFC phasing and the established one-ticket-per-PR pattern. - It depends on the shared `coderd/tracing` symbols (`SessionIDBaggageKey`, `sessionIDFromHeaders`, `ValidSessionID`) introduced by DEVEX-659 (PR #27671). - **Decision:** #27671 is not merged yet, so stack `devex-660-...` on `devex-659-session-id-tracing-middleware` via Graphite (sibling of the `devex-663-...` frontend branch). - Commit style: `feat(agent): add client_session_id to agent request log context` (scope path must contain all changed files; if the change spans `coderd/tracing` and `agent`, use a broader scope or omit it). - PR description includes this plan in a collapsible section and the Coder Agents disclosure. ## Open questions / risks 1. ~~**Which base?**~~ Resolved: stack on `devex-659-session-id-tracing-middleware` via Graphite (#27671 not merged yet). 2. **Agent test harness.** Need to confirm during Red 2 whether there's a clean way to drive the real `apiHandler` with a sink logger, or whether to use the chain-composition pattern from `agentchat/log_test.go`. 3. **No live source of agent baggage yet for the web terminal.** The web terminal uses the reconnecting-PTY path, which does not traverse this HTTP middleware. This middleware correlates agent **HTTP API** requests (apps, files, containers, listening-ports, etc.) whose clients send `client_session_id` baggage per RFC #3. Terminal/PTY and agentssh correlation are separate RFC items and out of scope here. </details> _Opened by Coder Agents on behalf of @aqandrew._ |
||
|
|
f208fc0c83 |
refactor: rename edit_files wire type to old_text/new_text (#28467)
The schema has advertised old_text/new_text since #25658, but the shared wire type still encoded search/replace. Decode accepts the deprecated keys only when both new fields are empty, through the pre-rename tags, so old coderd and cached MCP schemas keep working. Marshal emits both key sets so old agents keep working after a coderd upgrade. Both shims are removed in the first release after Coder Agents GA (2026-09). The Go field rename is a deliberate source break: FileEdit carries no codersdk stability guarantee. Fixes CODAGT-523 Refs CODAGT-483 |
||
|
|
2a8e390f0c |
refactor: replace most usage of ptr.Ref with new (#28282)
|
||
|
|
6093705476 |
fix: use old_text/new_text vocabulary across edit_files (#28626)
The schema has advertised old_text/new_text since #25658, but agent error strings and hints still said "search string", directing the model toward field names it is not sending. Fixes CODAGT-523 |
||
|
|
8cd7f9ad4e |
fix(agent/agentcontext): preserve skill source precedence (#28443)
Duplicate workspace skills were sorted by source path before chat hydration, so alphabetical paths could override the order configured in `CODER_AGENT_EXP_SKILLS_DIRS`. Resolve duplicate valid skill names before deterministic sorting and persistence, with user-declared sources evaluated in configured order ahead of built-in and working-directory discovery. This PR was generated by Coder Agents. |
||
|
|
5ca0143992 | refactor: upgrade golangci-lint to v2.0.2 (#28416) | ||
|
|
903d7b756d |
feat: add workspace agent session count protocol (#28125)
Phase 2 of the Scalable Approach for Adding New IDE Session Types RFC, tracked in #27410. Adds a session_counts map to Stats on the Agent API, so an agent can report a count per app name instead of the four fixed fields, which are now marked deprecated. Bumps the API to v2.11. - coderd normalizes names on ingest, caps distinct entries, and sums the overflow under unknown, so an arbitrary client name cannot blow up cardinality. - Agents predating v2.11 set the fixed fields instead, never both, and the ingest path falls back to them. Nothing sends session_counts yet. The agent starts populating it in #28338. |
||
|
|
c767cc5198 |
refactor: normalize workspace agent session metadata (#28124)
Phase 1 of the Scalable Approach for Adding New IDE Session Types RFC, tracked in #27410. Gives agent session accounting one canonical vocabulary for app names, so later work can report a count per app without the agent and the server disagreeing about what an app is called. - Adds codersdk/appname.go: NormalizeAppName for storage and lookup, and AppFamilyName for the places that need a bounded value, such as a Prometheus label or the Connection_Type enum. - agentssh.Server keeps session counters in a map keyed by normalized name instead of three fixed atomics, dropping entries at zero. - Drops MagicSessionType. Sessions carry plain app names, and unrecognized ones flow through as themselves rather than collapsing to unknown. Wire behavior is unchanged: the agent still reports the four session_count_* fields over Agent API 2.10. |
||
|
|
5480299cef |
fix: serialize empty MCP tool properties as {} not null for OpenAI (#28380)
## Summary
Fixed a bug where MCP tools with an empty `properties` schema had their
tool definitions sent to OpenAI with `"properties": null`, causing
OpenAI to reject the request.
## Problem
When an MCP server reports a tool with an empty input schema, e.g.:
```json
{
"type": "object",
"properties": {},
"required": []
}
```
Coder was forwarding the tool definition to OpenAI as:
```json
{
"type": "object",
"properties": null
}
```
OpenAI's function-calling API rejects `properties: null`, making these
tools unusable with OpenAI models.
## Root cause
The empty `properties` object collapsed to Go `nil` at two layers:
1. `agent/x/agentmcp/manager.go` `toolInputSchemaMap` stripped the
present-but-empty `"properties": {}` (guarded by `len(properties) > 0`),
so the wire copy lost it entirely.
2. `coderd/x/chatd/chatloop/chatloop.go` `buildToolDefinitions` embedded
`info.Parameters` directly into the input schema. When nil,
`encoding/json` marshals it as `null`.
## Fix
- `buildToolDefinitions` now substitutes an empty object when
`Parameters` is nil, mirroring the existing `required` guard (the sink,
protects all tool sources).
- `toolInputSchemaMap` now preserves an empty `properties` object
instead of dropping it (the upstream producer).
## Tests
Added regression tests (failing before, passing after) covering both
layers and asserting the schema serializes to
`{"type":"object","properties":{}}`:
- `TestBuildToolDefinitionsNilPropertiesBecomesEmptyObject`
- `TestToolInputSchemaMapPreservesEmptyProperties`
-
`TestWorkspaceMCPToolInfosFromResources/EmptyPropertiesYieldsEmptySchema`
---
*This PR was generated by Coder Agents.*
|
||
|
|
4a7a0a3348 | feat: label process_output rows with the process command (#28300) | ||
|
|
166d92ba73 |
fix: bound request body size on JSON API endpoints (#28168)
## Summary `httpapi.Read` decoded request bodies with no size limit, so a single request could allocate memory without bound. This adds a 4 MiB default ceiling, leaves the endpoints that legitimately need more explicitly exempted, and counts the rejections so a limit set too tight is visible. This is the first of three PRs split out of #28048, covering the endpoints that answer in `codersdk.Response` shape. The OAuth2 decode paths (RFC 6749, RFC 7591) and the SCIM ones (RFC 7644) answer in their own error shapes and follow in separate PRs, along with the lint rule that pins the invariant. Closes PLAT-463. Remediates SEC-416 (CWE-770, CVSS 7.5) and SEC-392. ## Problem `httpapi.Read` calls `json.NewDecoder(r.Body).Decode(value)` with no ceiling, and no middleware in the chain bounds body size. The exposure is pre-authentication: login, OTP, and first-user creation all read a body before any authorization decision is reached. The existing rate limiter bounds request *rate*, which is orthogonal to the memory a single admitted request may consume. ## Fix `Read` is split into `Read` and `ReadLimit`. `ReadLimit` wraps `r.Body` in an `http.MaxBytesReader` and keeps the existing decode and validate logic; `Read` delegates to it with a new `DefaultMaxRequestBodyBytes` of 4 MiB, which covers the 124 remaining non-test callers at a single site. `http.MaxBytesReader` composes as tightest-wins, so the handlers that pre-wrapped their own bodies pass their limit to `ReadLimit` rather than wrapping, and each keeps its previous ceiling byte for byte. That matters most for the bulk secrets import at `8 * MaxSecretsFileBytes`: an unconditional wrap inside `Read` would have silently halved it to the default. `TestImportUserSecretsBodyLargerThanDefaultLimit` is the regression guard for that specific failure, and `TestMaxBytesReaderNesting` pins the composition behavior the whole requirement rests on. Every rejection site calls `httpapi.RecordRequestBodyLimit`, which names the limit that tripped on the request's existing log line and marks the request so `coderd_api_requests_too_large_total{reason="request_body"}` counts body rejections apart from the 413s coderd answers for other causes, such as agent log storage overflow. A limit set too tight for a legitimate payload therefore surfaces without waiting for a user report. The limit is a constant rather than a deployment option: an operator raising it to unblock something would reopen the vulnerability as configuration, where a security scan will not find it. A legitimate 413 is answered with a targeted `ReadLimit` on that endpoint. ## Behavior change `POST /api/v2/files` now answers 413 rather than 400 when a request body exceeds `HTTPFileMaxBytes`. It installed that bound already but reported the rejection as a read failure, which leaked the stdlib `http: request body too large` string through `Detail` and kept the largest limit in the tree off the metric. The separate 413 for an oversized expanded archive is unchanged. The task log snapshot endpoint now answers 413 rather than 400 when its 64 KiB cap is exceeded. Routing it through `ReadLimit` also changes its decode-failure message from "Failed to decode request payload." to "Request body must be valid JSON.", which is what every other endpoint answers. Its tests are updated to match both. `coderd_api_requests_too_large_total` is new, so there is no existing query to migrate. It counts the 413s coderd answers, labeled `method`, `path`, and `reason`. `reason="request_body"` is a rejection by one of the limits above; `reason="other"` is a 413 that has nothing to do with body size, such as agent log storage overflow. ## Reading this The commits are ordered to be read in sequence. Commits 1 and 2 are the security fix; commits 3 to 5 are the observability consequences, and commit 3 is the one that touches dashboards. Commit 7 documents the limit on the REST API reference index. Commits 6 and 8 add and revert an exhaustive `@Failure 413` annotation pass, which buried the fix under its regenerated swagger, and cancel out. |
||
|
|
af90d8e2be |
fix(agent/agentscripts): create missing log_path parent directory (#28166)
Previously, a `coder_script` whose `log_path` pointed under a directory
that did not yet exist failed before the script ran, with no per-script
log output. `OpenFile(logPath, O_CREATE|O_RDWR, 0o600)` creates the log
file but not its parent directories, so the open returned `ENOENT`. The
failure only surfaced in the agent log (`startup script(s) failed` /
`shutdown script(s) failed`) and never reached the script's own UI logs,
which made it look like a silent failure.
This creates the resolved parent directory with
`MkdirAll(filepath.Dir(logPath), 0o700)` before opening the log file, so
the script runs and its log is written. `0o700` matches the existing
script data-dir and secret-file directory conventions in this package.
Resolution of `~`, environment variables, and paths relative to `LogDir`
is unchanged; only the parent directory is now created.
Fixes coder/coder#21986
<details><summary>Implementation notes and validation</summary>
**Change**
* `agent/agentscripts/agentscripts.go`: in `(*Runner).run`, after the
full `logPath` resolution and before `OpenFile`, create the parent
directory:
```go
logDir := filepath.Dir(logPath)
if err = r.Filesystem.MkdirAll(logDir, 0o700); err != nil {
return xerrors.Errorf("create script log file directory %q: %w", logDir,
err)
}
```
**Regression test**
* `agent/agentscripts/agentscripts_test.go`:
`TestExecuteCreatesMissingLogDir` runs a script with a nested,
nonexistent `LogPath` and asserts the streamed output and that the log
file is created.
* The test uses `afero.NewOsFs()` on purpose: `afero.NewMemMapFs()`
auto-creates parent directories on `OpenFile`, so it cannot reproduce
the reported failure.
* Verified red without the fix (`open .../does/not/exist/install.log: no
such file or directory`) and green with it.
**Local validation**
* `gofmt` clean, `go vet`, `go build`, `golangci-lint run` on the
package, and `go test -race ./agent/agentscripts/` all pass.
**End-to-end**
* Validated on a dev instance with a template whose
`coder_script.log_path` targets a nested directory that does not exist.
The agent created the parents with mode `0700` and wrote the log file;
the workspace agent reported healthy.
**Prior attempts**
* [#22796](<https://github.com/coder/coder/issues/22796>) and
[#25545](<https://github.com/coder/coder/issues/25545>) proposed the
same directory-creation approach. Both were closed for non-technical
reasons (a low-effort AI PR and a stale community PR), not rejected on
the merits. This supersedes them, authored by the issue owner, using
`0o700` and adding a regression test.
</details>
---
*Raised on behalf of* @35C4n0r *by Coder Agents.*
|
||
|
|
7720e283f5 |
feat(agent/x/agentmcp): migrate workspace agent MCP client to official Go SDK (#28059)
## Stack Context PR 4 of 6 in a stack that migrates every Coder MCP surface from the archived `github.com/mark3labs/mcp-go` library to the official `github.com/modelcontextprotocol/go-sdk` v1.7.0. Stack: #28056 -> #28057 -> #28058 -> #28059 -> #28060 -> #28061 ## Why The workspace agent MCP manager now stores `*mcp.ClientSession` per configured server. - stdio servers use `mcp.CommandTransport` with an `exec.Cmd` built from Coder's `agentexec.Execer`, preserving environment enrichment; the command uses the manager's parent context so a stdio subprocess outlives the connect handshake and stops when the session closes. - HTTP and SSE servers use header-injecting HTTP clients. - Binary tool content is re-encoded to base64 for the agent API because the official SDK decodes it into raw bytes. - The reload test now triggers config diffs via an environment variable because the official SDK drops connections on non-protocol stdout output (flags like `-test.v` made the fake server chatty). > Mux created this PR on Mike's behalf. |
||
|
|
87494c4f88 |
test(agent): de-flake TestAgent_Session_EnvironmentVariables (#27803)
The environment-variable and secret-injection tests reused one long-lived SSH shell, so a closed channel caused later checks to fail with `EOF` and could allow scan-based assertions to pass without finding a value. They now share only the SSH client and use a fresh, deadline-bound session for each variable, isolating failures while preserving environment-precedence coverage. Closes https://linear.app/codercom/issue/PLAT-310. Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder. |
||
|
|
8a4adeec32 |
fix(agent): detect IPv6-bound listening ports (#27765)
Closes https://github.com/coder/coder/issues/15675 Dev servers that bind to the IPv6 wildcard address (Next.js, Node's default `http.Server`, Go's `net.Listen` on wildcard addresses, and others) never showed up in the dashboard Ports panel, even though they were listening and reachable. The agent's port scanner only called `netstat.TCPSocks`, which reads `/proc/net/tcp` (IPv4 only); an `[::]` dual-stack socket lives exclusively in `/proc/net/tcp6`, so the panel reported "No open ports were detected." Also scan `netstat.TCP6Socks` and merge the results into the existing dedupe loop. The IPv6 scan failure is non-fatal so hosts with IPv6 disabled (missing `/proc/net/tcp6`, Windows with the v6 stack off) keep their IPv4 results instead of the Ports panel 500ing. Both captures below: `python3 -m http.server 5123 --bind ::` running in the same workspace, built from main vs this branch ([full recordings](https://github.com/coder/coder/tree/recordings/recordings/ipv6-listening-ports)). ## Before  ## After  <details> <summary>Debugging and decision log</summary> - Reproduced on a dogfood workspace: `next-server` listening on `*:3000` per `ss -tlnp`, `curl` returning 200, but `GET /api/v2/workspaceagents/{agent}/listening-ports` returning `{"ports": []}`. Port 3000 (hex `0BB8`) present in `/proc/net/tcp6`, absent from `/proc/net/tcp`. - Confirmed `agent/ports_supported.go` only calls `netstat.TCPSocks`; the library's `TCP6Socks` (parses `/proc/net/tcp6` on Linux, `GetTcp6Table2` on Windows) was never referenced. - Control test: an IPv4-bound (`0.0.0.0`) listener was detected correctly, isolating the bug to the missing IPv6 scan. - Made the IPv6 scan failure non-fatal after review: returning an error would break the entire ports endpoint (HTTP 500 on every poll) on IPv6-disabled hosts, a regression from the current behavior of "IPv4 ports only." Silent fallback matches the spirit of `ports_unsupported.go`, which returns an empty list rather than erroring. - The fix lives in the OS-backed `osListeningPortsGetter` behind the `ListeningPortsGetter` interface from #20842, so the fake used by coderd tests is unaffected. - Dedupe by port in the existing `seen` map covers dual-stack sockets that appear in both tables on Windows. - `TestOSListeningPortsGetter_IPv6` listens on `[::]:0` and asserts detection; it skips when the host can't bind IPv6. Verified it fails against the pre-fix code. </details> > 🤖 This PR was opened by [Coder Agents](https://coder.com/docs/ai-coder/agents) on behalf of @bpmct. |
||
|
|
dc31791c88 |
test: don't use ptytest for client side of SSH session tests (#27681)
In our initial batches of test refactors, I left the SSH session tests using `ptytest` because I (erroneously) thought that we still needed a client side PTY when the SSH server creates a PTY. This is incorrect and plain in-process IO is fine on the client side. closes https://github.com/coder/internal/issues/1400 (again)<!-- If you have used AI to produce some or all of this PR, please ensure you have read our [AI Contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING) before submitting. --> |
||
|
|
66e6f40b8b |
chore: rename agent firewall flags (#27231)
* Alias --boundary-log-proxy-socket-path to --agent-firewall-log-proxy-socket-path * Also alias CODER_AGENT_BOUNDARY_LOG_PROXY_SOCKET_PATH to CODER_AGENT_FIREWALL_LOG_PROXY_SOCKET_PATH * Also Rename related variables and symbols to reflect the new name. <!-- If you have used AI to produce some or all of this PR, please ensure you have read our [AI Contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING) before submitting. --> |
||
|
|
35ade9e3d2 |
feat: collect workspace logs in support bundles (#26694)
Add workspace-side file collection to `coder support bundle` via repeatable --workspace-file flags. The agent resolves the requested paths or globs inside the remote workspace and streams back a tar with a manifest and the collected files; nothing is read from the machine running the command. - Add POST /api/v0/bundle-files to the agent's agentfiles package. - Expand env vars in the agent's environment; paths must then be absolute or start with ~/ (the agent user's home directory). - Support ** globs and tail oversized files. - Record requested patterns, per-path errors, truncation, and the applied limits in a manifest. - Unpack the archive into the bundle under agent/workspace_files/, recording dropped entries in collection_errors.txt. - Write a manifest-only archive marking collection as unsupported for agents that predate the endpoint. - Bound collection: 64 KB request body, 10000 files, 10 MiB per file, 100 MiB total including archive overhead, 110 MiB client-side read cap, 5 minute timeout. Closes #26020 |
||
|
|
b33ff2d851 | fix: redact env var values in agent debug manifest endpoint (#26904) | ||
|
|
953091c7bc |
refactor: use sync.WaitGroup.Go in tests (#26671)
Migrate `wg.Add(1); go func() { defer wg.Done(); ... }()` to
`wg.Go(func() { ... })` in tests.
Where the prior pattern passed the loop variable explicitly via a
closure parameter (`go func(id int) { ... }(i)`), drop the parameter and
reference the loop variable directly. Per-iteration loop variables since
Go 1.22 make this safe.
|
||
|
|
1742003785 |
fix(agent): gate workspace context collection until the agent is ready (#26715)
## 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.
|
||
|
|
bafc86310c |
fix(agent/agentcontext): identify context sources by lexical path (#26616)
## What Identify agent workspace-context **sources** by their lexical (configured) path so `coder exp chat context list` no longer shows the same directory twice, and so a source is shown as the path the operator actually configured. ## Why (the bug) Source identity was the canonical path from `CanonicalizePath`, which resolves symlinks via `EvalSymlinks` **only when the target exists**. That makes canonicalization time-dependent: - At boot the agent seeds sources from `CODER_AGENT_EXP_*_DIRS`. If `~/.coder/skills -> ~/my-agent/agent-rules/skills` and the target does not exist yet (a startup script creates it later), `~/.coder/skills` canonicalizes to the lexical `/home/coder/.coder/skills`. - After the manifest lands (or the target is added directly), the same configured source canonicalizes to the resolved `/home/coder/my-agent/agent-rules/skills`. The same configured source produced two different strings, so dedupe keyed on the string registered both and the list showed one directory twice. Resolving symlinks for identity is also misleading on its own (per @mafredri's review): a source added by a symlink path appears in the list as its resolved target, as if that target had been added explicitly. ## How Source identity is now the **lexical** path: cleaned, `~`-expanded, absolute, with symlinks **not** resolved (new `lexicalPath`; `CanonicalizePath` is refactored to build on it). `AddSource`, `SeedSources`, `HasSource`, `RemoveSource`, and boot seeding all key on this stable identity. `AddSource` still **validates** the resolved (`CanonicalizePath`) path against the allowed roots, so a symlink cannot escape them. Only the identity/display path changed. This replaces the earlier `os.SameFile`/inode dedupe, which was unstable and failed on Windows runners. ## Testing - `go test ./agent/agentcontext/` (full package) and `go vet` pass; `gofmt` clean. - `TestManager_SourceIdentityIsLexicalAndStable`: adds the same symlinked source before and after its target exists and asserts one source whose path is the lexical link (skipped on Windows, matching the package's other symlink tests). - Existing `TestCanonicalizePath_FollowsSymlinks` and `TestValidateSourcePath_*` confirm symlink resolution and the security boundary are unchanged. <details> <summary>Related review findings</summary> Fixes the "duplicate symlinked paths in `context list`" issue from the chat-context system review and the dedupe-ordering question (lexical identity preserves first-come-first-served order). Showing the configured path for **resources** (not just sources) and restoring scope-based skill precedence are separate, larger changes tracked elsewhere. </details> --- *This PR was created by Coder Agents on behalf of @kylecarbs.* |
||
|
|
a1ec9df345 |
test(agent/agentcontext): use resolved temp dirs in symlink tests (#26602)
These symlink resolver tests build expected paths from `t.TempDir()`, but the resolver canonicalizes symlink targets with `filepath.EvalSymlinks`. On macOS, `/var` resolves to `/private/var`, so the raw temp dir path can disagree with the resolver output and flake. Use `testutil.TempDirResolved` in the symlink-sensitive tests so the expectations are canonicalized the same way. Closes https://github.com/coder/internal/issues/1574 Closes ENG-2849 |
||
|
|
27ecd17991 |
refactor: consolidate agent MCP onto a single persistent engine (#26599)
Two MCP code paths both spawned the servers declared in a workspace's `.mcp.json`: the persistent engine in `agent/x/agentmcp` (which owns tool-call execution via `CallTool`) and an ephemeral one-shot runner in `agent/agentcontext` (`mcprunner.go`) that connected, listed tools, and immediately closed each server purely for discovery. Every declared server was launched twice, and the discovery path duplicated the engine's `.mcp.json` parse, transport-build, env-resolve, and connect logic. This makes `agent/x/agentmcp` the single persistent MCP engine. The `agentcontext` manager now reads that engine's per-server catalog in-process through an injected `MCPCatalog` option and surfaces each server as a `KindMCPServer` resource. The engine wires `SetOnReload` to the manager's `Trigger`, so a reload (startup connect or `.mcp.json` edit) re-resolves and re-pushes the pinned resources. Tool-call execution is unchanged: it still flows through the engine's `CallTool` over `POST /api/v0/mcp/call-tool`. The now-dead HTTP discovery surface is removed: the agent `GET /api/v0/mcp/tools` route with `agentmcp.API.handleListTools`, and `workspacesdk.AgentConn.ListMCPTools` with `ListMCPToolsResponse` (mock regenerated). The change nets roughly `-1370` lines, mostly the deleted duplicate runner and its tests. <details> <summary>Decision log</summary> The merge of #26585 made pinned `chat_context_resources` the sole source of workspace context, which surfaced the duplicate spawning. Two options were considered: - **Option A + dependency injection (chosen):** keep `agent/x/agentmcp` as the single persistent engine; `agentcontext` consumes its catalog in-process and stays the orchestrator/owner at the API boundary (it still pushes `KindMCPServer` resources). This is low-risk because `agentcontext` already exposed the `resolver.MCPResources` seam, so the change just rebinds it from the ephemeral runner to the shared engine. - **Option B (rejected):** reimplement persistent pooling, reconnect, singleflight, and race handling inside `agentcontext` and delete `agentmcp`. Too broad, and it discards the engine's tested lifecycle for no behavioral gain. `agentcontext`'s discovery was never what kept servers alive; its runner closed each server immediately after listing tools. The component holding persistent connections was always `agentmcp`, which is why execution already lived there. Consolidating onto it removes the duplicated stack rather than a whole package: both packages survive with distinct roles (`agentmcp` is the engine, `agentcontext` is the orchestrator/owner). </details> Coder Agents generated on behalf of @kylecarbs |
||
|
|
0f37522e6f |
refactor(agent/agentcontext): fixed-location shallow context discovery (#26596)
## Problem
`agent/agentcontext` resolved workspace context by walking the working
directory recursively (depth 8) and matching files by basename. This
over-injected context:
- Instruction-file matching was case-insensitive, so the generated
`docs/reference/api/agents.md` was treated as an instruction file.
- Symlinked instruction files (`CLAUDE.md`, `.cursorrules` ->
`AGENTS.md`) shipped as duplicate resources.
- Nested `AGENTS.md` (e.g. `site/AGENTS.md`) were collected from
anywhere in the tree.
- Skills were discovered from *any* `skills/` directory anywhere in the
tree, and `.mcp.json` from any depth.
Resolving the repo root produced six instruction sources for what was
effectively one file of guidance, plus skills/MCP found by an open-ended
walk.
## What changed
Replace the recursive scan with **fixed-location, shallow** discovery.
Each scan root is inspected at its top level only: the resolver never
descends into subdirectories and never climbs to a parent. Additional
directories are added explicitly as sources (HTTP API) or via the
`CODER_AGENT_EXP_*_DIRS` seeding env vars.
- **Single working-dir scan root.** The working directory is one scan
root. Instruction files and `.mcp.json` are read only at its top level.
- **Fixed-location skills.** Skills are discovered only from `skills`,
`.agents/skills`, `.claude/skills`, `.codex/skills` (one skill per
immediate subdir with a `SKILL.md`), not from arbitrary `skills/`
directories.
- **Case-sensitive instruction names.** Exact
`AGENTS.md`/`CLAUDE.md`/`.cursorrules`; a lower-case `agents.md` is
ignored.
- **Symlink dedup.** Resources are attributed to their resolved target,
so symlinked `CLAUDE.md`/`.cursorrules` collapse into the single
`AGENTS.md`.
- **Watcher** mirrors the same fixed-location set instead of recursively
watching every scan root (no more walking `node_modules`).
- The recursive `walkDir`, `skipDirNames`, `MaxScanDepth`, and
`isSkillsContainer` are removed.
Resolving the repo root now yields `AGENTS.md`, `.mcp.json`, and the
`.agents/skills`/`.claude/skills` skills, with no nested
instruction-file noise.
## Behavior change
`site/AGENTS.md` is no longer auto-injected when the working dir is the
repo root. It loads when the working dir **is** `site/` (its top level),
or when `site/` is added as an explicit source. There is intentionally
**no walk-up** to a `.git` project root: an agent started in a
subdirectory does not auto-inherit ancestor `AGENTS.md`; those
directories are added explicitly.
<details>
<summary>Verification & decision log</summary>
**codex research (confirmed via source).** Instruction files: codex
walks up to the first `.git` ancestor and reads root->cwd, one file
per directory, exact-cased names (`codex-rs/core/src/agents_md.rs`).
Skills: fixed roots (`.agents/skills`, `.codex/skills`,
`$CODEX_HOME/skills`, ...) with bounded in-root recursion
(`core-skills/src/loader.rs`). MCP: `.codex/config.toml` via walk-up; a
project `.mcp.json` is not a runtime source in codex. No resource type
triggers an unbounded downward walk.
**Decisions.**
- Adopt codex's fixed-location, shallow discovery (case-sensitive names,
symlink dedup, top-level-only files, container-only skills).
- **Deliberately omit codex's walk-up to the `.git` project root.** In
Coder the working dir is the scan root and extra directories are added
explicitly (HTTP API / `CODER_AGENT_EXP_*_DIRS`), so the implicit
ancestor climb added surprise without benefit (e.g. `context add ./site`
should scan `./site`, not the repo root).
- Keep `.mcp.json` (codex uses `config.toml`, intentionally not added).
- Include `.claude/skills` and `.codex/skills` in the container list so
the repo's existing `.claude/skills` skills are not regressed; skills
recurse one level inside a container.
**Tests.** `TestManager_WorkingDirScannedShallow` (working dir read at
top level; ancestor root and nested subdir both excluded);
`TestResolver_SkillsOnlyFromFixedContainers`,
`TestResolver_MCPConfigOnlyAtScanRoot`,
`TestResolver_SymlinkedInstructionFilesDeduplicated`,
`TestResolver_InstructionFilesOnlyAtScanRoot`,
`TestResolver_InstructionNamesAreCaseSensitive`. Cap tests use multiple
scan roots.
**Local checks.** `gofmt`, `go vet`, `golangci-lint`, `go test -race`,
and `make lint/emdash` pass for the package.
</details>
---
🤖 Generated by Coder Agents on behalf of @kylecarbs.
|
||
|
|
f5cb2e547e |
feat: include rotated agent logs in support bundles (#26055)
Support bundles previously captured only the active coder-agent.log, losing history across agent restarts. Add an optional `after` filter to the agent's /debug/logs endpoint: without it the endpoint is unchanged (active log only, 10 MiB cap); with it the response includes the active log plus rotated coder-agent-*.log files modified after the cutoff, newest first. Support bundles request the last 24h. Closes #25395 |
||
|
|
2f8bba792a |
feat: push MCP server context and tools from agentcontext (#26533)
## What Live MCP servers and their tools now flow into the `agentcontext` snapshot and are pushed to coderd via `PushContextState`, stored alongside instruction files and skills. Previously the resolver's MCP seam was unimplemented, so live MCP tool lists never reached the pushed snapshot. `agentcontext` is now **fully self-contained** for MCP: it connects to the MCP servers declared in the `.mcp.json` files its own watcher already discovers, lists their tools, and emits `KindMCPServer` resources. It does **not** depend on or modify `agent/x/agentmcp` — that package is left pristine and keeps serving the agent's MCP HTTP API. The two MCP paths run independently, which means the legacy package can be deleted later without touching this code. ## How - **Self-contained runner** (`agentcontext/mcprunner.go`): a one-shot MCP client (connect → initialize → list tools → close) with its own `.mcp.json` parser. A Manager goroutine (`runMCPSync`) reloads it whenever the discovered `KindMCPConfig` `path:contenthash` set changes, then re-resolves so the new tools are published. Per-server connects run in parallel (bounded) with a per-server timeout; a server that fails to connect is recorded as a failure rather than aborting the batch. Each connect also force-kills its subprocess on close, because mcp-go's stdio `Close()` closes stdin and then blocks on `cmd.Wait()` with no kill — a server that ignores stdin-close would otherwise stall the whole reload loop. - **Resource production** (`agentcontext/mcp.go`): `buildMCPServerResources` turns the runner's non-blocking per-server snapshot into `KindMCPServer` resources. Connected servers carry their sorted tools (`StatusOK`); failed servers surface as `StatusUnreadable` issues instead of vanishing; connected-but-no-tools-yet are skipped until a later reload. The content hash is tool-set sensitive. The resolver consumes this through a plain `MCPResources func() []Resource` field (no `MCPProvider` interface). - **Tool names**: emitted exactly as the server reports them. Flattening into a single namespace (e.g. `server__tool`) is left to the control plane in the next step, since each resource already carries the server name. - **Drift**: MCP resources are excluded from the snapshot aggregate/drift hash (`driftResources`). MCP servers connect asynchronously after boot; without this, a server finishing its connect would dirty every hydrated chat even though nothing the user pinned changed. - **Wiring** (`agent.go`): the manager is given `ManagerOptions.MCPExecer`/`MCPUpdateEnv`; `agent/x/agentmcp` is untouched. - **Config validation**: a structurally broken `.mcp.json` surfaces as `StatusInvalid` rather than silently dropping all its servers. coderd already persists `mcp_server`/`mcp_config` resource bodies (including tools), so no coderd or proto changes were required. ## Testing - **Unit**: `buildMCPServerResources` (grouping/sort/skip/failed/hash sensitivity), MCP resources applied via the resolver seam, MCP exclusion from the aggregate hash, `.mcp.json` parsing (transport inference, env expansion), `toolInputSchema`, and `mcpConfigSet` change detection. - **Proto serialization** (`TestDRPCPusher_HappyPathSerializesAllFields`): a `KindMCPServer` resource (tools + input schema) round-trips through `PushContextState` into the `MCPServerBody` wire form, asserting the server name, tool name/description, and the decoded `input_schema`. - **Manager-level, real subprocess** (`TestManager_MCPServerToolsInSnapshot`): a `.mcp.json` points at a re-exec'd fake stdio MCP server; the runner connects it and its `echo` tool surfaces as a `KindMCPServer` resource in the Manager snapshot — the same snapshot pushed to coderd — exercising `runMCPSync` and the resolver wiring end to end. - **Regression** (`TestManager_MCPServerHangingCloseDoesNotStall`): the fake server ignores stdin-close; the test asserts its tool still surfaces, proving the runner force-kills the subprocess instead of stalling the reload. Verified to fail without the fix. - All pass under `-race`; `go build ./...`, `go vet`, and `golangci-lint` are clean on the touched packages. ## Scope / follow-ups This is the agent-side production+push half. The chatd consumer (reading the pinned MCP resources for prompt/tool injection, including any server-prefix flattening of tool names) and removing the legacy `workspaceMCPToolsCache` pull path remain follow-ups, per the RFC rollout. While both `agent/x/agentmcp` and `agentcontext` exist, stdio MCP servers are spawned by both; this is intentional and temporary until `agentmcp` is removed. <details> <summary>Implementation plan and decisions</summary> **Goal:** produce live MCP server resources (with tools) from `agentcontext` and push them to coderd. **Starting state (main):** proto (`PushContextState`, `MCPServerBody`, `MCPTool`), the drpc adapter, coderd storage (`workspace_agent_context_resources`, body kind `mcp_server`), and the resolver's MCP seam already existed; nothing implemented the seam or fed live tools into the snapshot. **Decision (agentcontext fully separate from agentmcp):** `agentcontext` starts and lists its own MCP servers using only the connect-and-list half of an mcp-go client, driven by the `.mcp.json` files its existing watcher discovers. It shares no state with `agent/x/agentmcp` and does not import it. Two earlier revisions of this branch were discarded: (1) relocating `agentmcp` into `agentcontext` (rejected — it duplicates config parsing and file watching `agentcontext` already does); (2) reading `agentmcp`'s cached server snapshot via new accessors (rejected — unnecessary coupling between two packages that should simply run independently while one is being retired). The temporary double-spawn of stdio servers is the accepted cost of keeping the two paths cleanly separated until `agentmcp` is removed. **Decision (no tool-name prefixing, no MCPProvider interface):** the agent pushes raw, unflattened data — server name plus verbatim tool names — and lets the control plane own any `server__tool` flattening. With a single self-contained producer, the `MCPProvider` interface was collapsed into a `func() []Resource` field on the resolver. **Invariants held:** no secrets (env/headers) in pushed resources, only server/tool metadata; MCP excluded from the drift hash; the seam is non-blocking so the resolver never stalls on MCP I/O. </details> --- *This PR was created by Coder Agents on behalf of @kylecarbs.* |
||
|
|
d5ec26beac |
chore: replace testing.Testing with flag lookup (#26552)
In our codebase we have an existing convention of using
`flag.Lookup("test.v")` instead of `testing.Testing()`. This avoids
pulling in the entire `testing` package. Another consequence: some of
our custom linters trigger upon import of the `testing` package which
can lead to unexpected linter errors.
|
||
|
|
992b1ffed1 |
feat(agent): serve context sources over the agent socket (#26526)
## Overview Split from #26466, scoped to **agent-only** changes. This PR exposes the agent's context sources and snapshots over the existing agent socket. There are no changes outside `agent/`. ## What's included - **agentsocket**: context source CRUD (`ContextSources`, `GetContextSource`, `AddContextSource`, `RemoveContextSource`) plus `GetContextSnapshot` and `ResyncContext` RPCs, with matching client methods and proto. The server receives the context `Manager` via `WithContextManager` and returns a clean error when it is absent. - **agentcontext**: the resync JSON response now carries the per-resource `Name`, keeping the HTTP resync payload in sync with the drpc `PushContextState` path in `agentsocket`. - **agent**: passes the context `Manager` to the socket server via `WithContextManager`. ## What's intentionally NOT here - No MCP wiring. There are no MCP additions in `agent.go` or `agentcontext`. MCP ownership will land later in `agentcontext`; this PR does not build on `agent/x/agentmcp`. - No changes to `agent/x/agentmcp` or the `agentcontext` resolver. The socket serves whatever context resources the `Manager` already resolves. <details> <summary>Context for reviewers</summary> This is one of several PRs split out of #26466. Earlier revisions also wired live MCP servers through the socket; that scope was removed so this PR stays purely socket + context plumbing inside `agent/`. The agentcontext resolver, `agent/x/agentmcp`, and `agent.go` MCP startup behavior are unchanged from `main`. </details> --- _Created by Coder Agents on behalf of @kylecarbs._ |