mirror of
https://github.com/coder/coder.git
synced 2026-09-21 20:51:01 +08:00
> 🤖 This PR was written by Coder Agents on behalf of Jake Howell. Closes [DEVEX-381](https://linear.app/codercom/issue/DEVEX-381/flake-test-tasksendwaitsforworkingappstate). Follow-up to #25648 and #25858, which addressed a different symptom of the same test. ## Symptom ``` task_send_test.go:348: context expired while waiting for trap: context deadline exceeded --- FAIL: Test_TaskSend/WaitsForWorkingAppState (26.02s) ``` Windows-only, on `test-go-pg (windows-2022)`. Reported four times since #25648 landed (2026-06-02, 2026-06-10, 2026-07-01). ## Root cause The test: 1. `setupCLITaskTest` inserts `workspace_app_status(state=idle)` at the end of setup. 2. `WaitsForWorkingAppState` then inserts `workspace_app_status(state=working)` before starting the CLI. 3. Both are persisted via `dbtime.Now()`, which rounds to microseconds. Windows `time.Now()` resolution is coarser than that (often ~1 ms or worse), so back-to-back calls frequently round to the same microsecond. 4. `GetLatestWorkspaceAppStatusesByWorkspaceIDs` has no tiebreaker: ```sql ORDER BY workspace_id, created_at DESC ``` Its sibling `GetLatestWorkspaceAppStatusByAppID` already uses `ORDER BY created_at DESC, id DESC` for exactly this reason. When the two rows collide, Postgres picks either. 5. On the failing runs, the query returned the `idle` row. `waitForTaskIdle` saw idle on the first poll, returned nil, `TaskSend` proceeded, and the CLI completed successfully in ~5 s. 6. But the test was blocked at `resetTrap.MustWait(ctx)` waiting for a **second** `ticker.Reset` that never happened. `WaitLong = 25s` elapsed, line 348 failed. CI log confirms the sequence: only one `Ticker.Reset(5s)` is caught, then `Ticker.Stop([]) call, matched 0 traps` (from `defer ticker.Stop()`), then the trap wait times out. This is the same class of flake Spike documented in #15923 and #21332 ("Windows in particular doesn't have high-resolution timers"), just hidden behind a SQL `ORDER BY`. ## Fix Two changes: 1. **`coderd/database/queries/workspaceapps.sql`**: add an `id DESC` tiebreaker to `GetLatestWorkspaceAppStatusesByWorkspaceIDs`, matching `GetLatestWorkspaceAppStatusByAppID`. Makes the query deterministic when `created_at` collides. 2. **`cli/task_test.go` / `cli/task_send_test.go`**: add a `withoutInitialAppStatus()` option to `setupCLITaskTest` and use it from `WaitsForWorkingAppState`. The test now inserts a single `working` row, so the collision cannot happen in the first place. Belt-and-braces with change 1. Comments in both places reference DEVEX-381 and #21332 so the next agent doesn't have to re-derive this. ## Verification - `go test ./cli -run 'Test_TaskSend' -count=1`: all 12 subtests pass, `WaitsForWorkingAppState` completes in ~5.6 s (was ~16 s previously due to a longer poll loop). - Stress: 20 sequential runs of `WaitsForWorkingAppState` on Linux, race-enabled binary, all pass in ~5.5 s each. - `go test ./coderd -run 'AppStatus|Task' -count=1` passes. - `go vet ./coderd/database/... ./cli/...` clean. - `make lint/emdash` clean. - `gofmt` clean. Not reproducible on Linux (real time between the two patches is orders of magnitude larger than microsecond); the Windows path is fixed by making the ordering deterministic and by not creating the collision in the first place. <details> <summary>Implementation plan & decision log</summary> ### Investigation 1. Pulled the failing job log for run `28483879823/job/84428355669`. 2. Traced the mock-clock trap sequence: one `NewTicker` and exactly one `Ticker.Reset(5s)` were caught, then `Ticker.Stop([]) call, matched 0 traps` fires (the `defer ticker.Stop()` on `waitForTaskIdle` return). This proves `waitForTaskIdle` returned after a single poll, not that the trap machinery hung. 3. The command exited with `<nil>` (`clitest.go:299: command "coder task send" exited with error: <nil>`) and a `POST /send` completed in 5.4 s. So the CLI succeeded; the test's own trap wait is what timed out. 4. The only `waitForTaskIdle` return-nil paths are `Active + CurrentState.State in {Idle, Complete, Failed}` and `Active + CurrentState == nil past 30s grace`. First observation of nil cannot be past 30s. So `TaskByID` must have returned `State == Idle`. 5. Traced `TaskByID` → `taskGet` → `workspaceData` → `GetLatestWorkspaceAppStatusesByWorkspaceIDs`. Found the missing tiebreaker; the sibling query one line above (`GetLatestWorkspaceAppStatusByAppID`) already had it. 6. Confirmed the two `PATCH /app-status` calls in the Windows log happened at `00:26:13.077` and `00:26:13.093`, well within Windows timer resolution. 7. Confirmed `dbtime.Now()` rounds to microseconds; Windows `time.Now()` doesn't have that precision, so `Round(time.Microsecond)` on two calls close together frequently produces equal values. ### Prior art from Spike - #15923: loosened `HeartbeatPeriod * 9/10` to `3/4` for Windows. - #21332: switched `assert.After` to `assert.NotBefore` because timestamps can equal on Windows. Both explicitly cite "Windows doesn't always have high-resolution timers available." ### Considered alternatives - **Only fix the test.** Works today but leaves the SQL query non-deterministic; another test that relies on `GetLatestWorkspaceAppStatusesByWorkspaceIDs` could hit the same collision. - **Only fix the SQL query.** Would give a stable answer but not necessarily the *right* one. If both patches share a `created_at`, `id DESC` picks whichever UUID sorted higher, still random with respect to insertion order. - **Make `dbtime.Now()` monotonic per process.** Cleanest at the source, but affects every timestamp in the database and has broader implications than a targeted flake fix. Going with both the query fix (defense in depth, matches existing pattern) and the test fix (eliminates the collision at the source) is the smallest change that closes the flake and hardens the query. ### Rejected commit-message scopes Changes touch both `cli/` and `coderd/database/`, so per AGENTS.md the scope is omitted for the cross-cutting commit and PR title. </details>
632 lines
22 KiB
Go
632 lines
22 KiB
Go
package cli_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"golang.org/x/xerrors"
|
|
|
|
agentapisdk "github.com/coder/agentapi-sdk-go"
|
|
"github.com/coder/coder/v2/agent"
|
|
"github.com/coder/coder/v2/agent/agenttest"
|
|
"github.com/coder/coder/v2/cli/clitest"
|
|
"github.com/coder/coder/v2/coderd"
|
|
"github.com/coder/coder/v2/coderd/coderdtest"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/database/dbfake"
|
|
"github.com/coder/coder/v2/coderd/util/ptr"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/codersdk/agentsdk"
|
|
"github.com/coder/coder/v2/provisioner/echo"
|
|
"github.com/coder/coder/v2/provisionersdk/proto"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
// This test performs an integration-style test for tasks functionality.
|
|
//
|
|
//nolint:tparallel // The sub-tests of this test must be run sequentially.
|
|
func Test_Tasks(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
// Given: a template configured for tasks
|
|
var (
|
|
ctx = testutil.Context(t, testutil.WaitLong)
|
|
client = coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
|
|
owner = coderdtest.CreateFirstUser(t, client)
|
|
userClient, _ = coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
|
|
initMsg = agentapisdk.Message{
|
|
Content: "test task input for " + t.Name(),
|
|
Id: 0,
|
|
Role: "user",
|
|
Time: time.Now().UTC(),
|
|
}
|
|
authToken = uuid.NewString()
|
|
echoAgentAPI = startFakeAgentAPI(t, fakeAgentAPIEcho(ctx, t, initMsg, "hello"))
|
|
taskTpl = createAITaskTemplate(t, client, owner.OrganizationID, withAgentToken(authToken), withSidebarURL(echoAgentAPI.URL()))
|
|
taskName = strings.ReplaceAll(testutil.GetRandomName(t), "_", "-")
|
|
)
|
|
|
|
for _, tc := range []struct {
|
|
name string
|
|
cmdArgs []string
|
|
assertFn func(stdout string, userClient *codersdk.Client)
|
|
}{
|
|
{
|
|
name: "create task",
|
|
cmdArgs: []string{"task", "create", "test task input for " + t.Name(), "--name", taskName, "--template", taskTpl.Name},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
require.Contains(t, stdout, taskName, "task name should be in output")
|
|
},
|
|
},
|
|
{
|
|
name: "list tasks after create",
|
|
cmdArgs: []string{"task", "list", "--output", "json"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
var tasks []codersdk.Task
|
|
err := json.NewDecoder(strings.NewReader(stdout)).Decode(&tasks)
|
|
require.NoError(t, err, "list output should unmarshal properly")
|
|
require.Len(t, tasks, 1, "expected one task")
|
|
require.Equal(t, taskName, tasks[0].Name, "task name should match")
|
|
require.Equal(t, initMsg.Content, tasks[0].InitialPrompt, "initial prompt should match")
|
|
require.True(t, tasks[0].WorkspaceID.Valid, "workspace should be created")
|
|
// For the next test, we need to wait for the workspace to be healthy
|
|
ws := coderdtest.MustWorkspace(t, userClient, tasks[0].WorkspaceID.UUID)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, ws.LatestBuild.ID)
|
|
agentClient := agentsdk.New(client.URL, agentsdk.WithFixedToken(authToken))
|
|
_ = agenttest.New(t, client.URL, authToken, func(o *agent.Options) {
|
|
o.Client = agentClient
|
|
})
|
|
coderdtest.NewWorkspaceAgentWaiter(t, userClient, tasks[0].WorkspaceID.UUID).WithContext(ctx).WaitFor(coderdtest.AgentsReady)
|
|
// Report the task app as idle so that waitForTaskIdle
|
|
// can proceed during the "send task message" step.
|
|
require.NoError(t, agentClient.PatchAppStatus(ctx, agentsdk.PatchAppStatus{
|
|
AppSlug: "task-sidebar",
|
|
State: codersdk.WorkspaceAppStatusStateIdle,
|
|
Message: "ready",
|
|
}))
|
|
},
|
|
},
|
|
{
|
|
name: "get task status after create",
|
|
cmdArgs: []string{"task", "status", taskName, "--output", "json"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
var task codersdk.Task
|
|
require.NoError(t, json.NewDecoder(strings.NewReader(stdout)).Decode(&task), "should unmarshal task status")
|
|
require.Equal(t, task.Name, taskName, "task name should match")
|
|
require.Equal(t, codersdk.TaskStatusActive, task.Status, "task should be active")
|
|
},
|
|
},
|
|
{
|
|
name: "send task message",
|
|
cmdArgs: []string{"task", "send", taskName, "hello"},
|
|
// Assertions for this happen in the fake agent API handler.
|
|
},
|
|
{
|
|
name: "read task logs",
|
|
cmdArgs: []string{"task", "logs", taskName, "--output", "json"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
var logs []codersdk.TaskLogEntry
|
|
require.NoError(t, json.NewDecoder(strings.NewReader(stdout)).Decode(&logs), "should unmarshal task logs")
|
|
require.Len(t, logs, 3, "should have 3 logs")
|
|
require.Equal(t, logs[0].Content, initMsg.Content, "first message should be the init message")
|
|
require.Equal(t, logs[0].Type, codersdk.TaskLogTypeInput, "first message should be an input")
|
|
require.Equal(t, logs[1].Content, "hello", "second message should be the sent message")
|
|
require.Equal(t, logs[1].Type, codersdk.TaskLogTypeInput, "second message should be an input")
|
|
require.Equal(t, logs[2].Content, "hello", "third message should be the echoed message")
|
|
require.Equal(t, logs[2].Type, codersdk.TaskLogTypeOutput, "third message should be an output")
|
|
},
|
|
},
|
|
{
|
|
name: "pause task",
|
|
cmdArgs: []string{"task", "pause", taskName, "--yes"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
require.Contains(t, stdout, "has been paused", "pause output should confirm task was paused")
|
|
},
|
|
},
|
|
{
|
|
name: "get task status after pause",
|
|
cmdArgs: []string{"task", "status", taskName, "--output", "json"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
var task codersdk.Task
|
|
require.NoError(t, json.NewDecoder(strings.NewReader(stdout)).Decode(&task), "should unmarshal task status")
|
|
require.Equal(t, taskName, task.Name, "task name should match")
|
|
require.Equal(t, codersdk.TaskStatusPaused, task.Status, "task should be paused")
|
|
},
|
|
},
|
|
{
|
|
name: "resume task",
|
|
cmdArgs: []string{"task", "resume", taskName, "--yes"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
require.Contains(t, stdout, "has been resumed", "resume output should confirm task was resumed")
|
|
},
|
|
},
|
|
{
|
|
name: "get task status after resume",
|
|
cmdArgs: []string{"task", "status", taskName, "--output", "json"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
var task codersdk.Task
|
|
require.NoError(t, json.NewDecoder(strings.NewReader(stdout)).Decode(&task), "should unmarshal task status")
|
|
require.Equal(t, taskName, task.Name, "task name should match")
|
|
require.Equal(t, codersdk.TaskStatusInitializing, task.Status, "task should be initializing after resume")
|
|
},
|
|
},
|
|
{
|
|
name: "delete task",
|
|
cmdArgs: []string{"task", "delete", taskName, "--yes"},
|
|
assertFn: func(stdout string, userClient *codersdk.Client) {
|
|
// The task should eventually no longer show up in the list of tasks
|
|
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
|
|
tasks, err := userClient.Tasks(ctx, &codersdk.TasksFilter{})
|
|
if !assert.NoError(t, err) {
|
|
return false
|
|
}
|
|
return slices.IndexFunc(tasks, func(task codersdk.Task) bool {
|
|
return task.Name == taskName
|
|
}) == -1
|
|
}, testutil.IntervalMedium)
|
|
},
|
|
},
|
|
} {
|
|
t.Logf("test case: %q", tc.name)
|
|
var stdout strings.Builder
|
|
inv, root := clitest.New(t, tc.cmdArgs...)
|
|
inv.Stdout = &stdout
|
|
clitest.SetupConfig(t, userClient, root)
|
|
require.NoError(t, inv.WithContext(ctx).Run(), tc.name)
|
|
if tc.assertFn != nil {
|
|
tc.assertFn(stdout.String(), userClient)
|
|
}
|
|
}
|
|
}
|
|
|
|
func fakeAgentAPIEcho(ctx context.Context, t testing.TB, initMsg agentapisdk.Message, want ...string) map[string]http.HandlerFunc {
|
|
t.Helper()
|
|
var mmu sync.RWMutex
|
|
msgs := []agentapisdk.Message{initMsg}
|
|
wantCpy := make([]string, len(want))
|
|
copy(wantCpy, want)
|
|
t.Cleanup(func() {
|
|
mmu.Lock()
|
|
defer mmu.Unlock()
|
|
if !t.Failed() {
|
|
assert.Empty(t, wantCpy, "not all expected messages received: missing %v", wantCpy)
|
|
}
|
|
})
|
|
writeAgentAPIError := func(w http.ResponseWriter, err error, status int) {
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(agentapisdk.ErrorModel{
|
|
Errors: ptr.Ref([]agentapisdk.ErrorDetail{
|
|
{
|
|
Message: ptr.Ref(err.Error()),
|
|
},
|
|
}),
|
|
})
|
|
}
|
|
return map[string]http.HandlerFunc{
|
|
"/status": func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(agentapisdk.GetStatusResponse{
|
|
Status: "stable",
|
|
})
|
|
},
|
|
"/messages": func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
mmu.RLock()
|
|
defer mmu.RUnlock()
|
|
bs, err := json.Marshal(agentapisdk.GetMessagesResponse{
|
|
Messages: msgs,
|
|
})
|
|
if err != nil {
|
|
writeAgentAPIError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
_, _ = w.Write(bs)
|
|
},
|
|
"/message": func(w http.ResponseWriter, r *http.Request) {
|
|
mmu.Lock()
|
|
defer mmu.Unlock()
|
|
var params agentapisdk.PostMessageParams
|
|
w.Header().Set("Content-Type", "application/json")
|
|
err := json.NewDecoder(r.Body).Decode(¶ms)
|
|
if !assert.NoError(t, err, "decode message") {
|
|
writeAgentAPIError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if len(wantCpy) == 0 {
|
|
assert.Fail(t, "unexpected message", "received message %v, but no more expected messages", params)
|
|
writeAgentAPIError(w, xerrors.New("no more expected messages"), http.StatusBadRequest)
|
|
return
|
|
}
|
|
exp := wantCpy[0]
|
|
wantCpy = wantCpy[1:]
|
|
|
|
if !assert.Equal(t, exp, params.Content, "message content mismatch") {
|
|
writeAgentAPIError(w, xerrors.New("unexpected message content: expected "+exp+", got "+params.Content), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
msgs = append(msgs, agentapisdk.Message{
|
|
Id: int64(len(msgs) + 1),
|
|
Content: params.Content,
|
|
Role: agentapisdk.RoleUser,
|
|
Time: time.Now().UTC(),
|
|
})
|
|
msgs = append(msgs, agentapisdk.Message{
|
|
Id: int64(len(msgs) + 1),
|
|
Content: params.Content,
|
|
Role: agentapisdk.RoleAgent,
|
|
Time: time.Now().UTC(),
|
|
})
|
|
assert.NoError(t, json.NewEncoder(w).Encode(agentapisdk.PostMessageResponse{
|
|
Ok: true,
|
|
}))
|
|
},
|
|
}
|
|
}
|
|
|
|
// setupCLITaskTestOpts controls optional behavior of setupCLITaskTest.
|
|
type setupCLITaskTestOpts struct {
|
|
skipInitialAppStatus bool
|
|
}
|
|
|
|
type setupCLITaskTestOpt func(*setupCLITaskTestOpts)
|
|
|
|
// withoutInitialAppStatus skips the default idle status, avoiding
|
|
// timestamp collisions on platforms with coarse time.Now() resolution.
|
|
func withoutInitialAppStatus() setupCLITaskTestOpt {
|
|
return func(o *setupCLITaskTestOpts) { o.skipInitialAppStatus = true }
|
|
}
|
|
|
|
// setupCLITaskTest creates a test workspace with an AI task template and agent,
|
|
// with a fake agent API configured with the provided set of handlers.
|
|
// Returns the user client and workspace.
|
|
// setupCLITaskTestResult holds the return values from setupCLITaskTest.
|
|
type setupCLITaskTestResult struct {
|
|
ownerClient *codersdk.Client
|
|
userClient *codersdk.Client
|
|
task codersdk.Task
|
|
agentToken string
|
|
agent agent.Agent
|
|
}
|
|
|
|
func setupCLITaskTest(ctx context.Context, t *testing.T, agentAPIHandlers map[string]http.HandlerFunc, opts ...setupCLITaskTestOpt) setupCLITaskTestResult {
|
|
t.Helper()
|
|
|
|
setupOpts := setupCLITaskTestOpts{}
|
|
for _, opt := range opts {
|
|
opt(&setupOpts)
|
|
}
|
|
|
|
ownerClient := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
|
|
owner := coderdtest.CreateFirstUser(t, ownerClient)
|
|
userClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
|
|
|
|
fakeAPI := startFakeAgentAPI(t, agentAPIHandlers)
|
|
|
|
authToken := uuid.NewString()
|
|
template := createAITaskTemplate(t, ownerClient, owner.OrganizationID, withSidebarURL(fakeAPI.URL()), withAgentToken(authToken))
|
|
|
|
wantPrompt := "test prompt"
|
|
task, err := userClient.CreateTask(ctx, codersdk.Me, codersdk.CreateTaskRequest{
|
|
TemplateVersionID: template.ActiveVersionID,
|
|
Input: wantPrompt,
|
|
Name: "test-task",
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
// Wait for the task's underlying workspace to be built.
|
|
require.True(t, task.WorkspaceID.Valid, "task should have a workspace ID")
|
|
workspace, err := userClient.Workspace(ctx, task.WorkspaceID.UUID)
|
|
require.NoError(t, err)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, userClient, workspace.LatestBuild.ID)
|
|
|
|
agentClient := agentsdk.New(userClient.URL, agentsdk.WithFixedToken(authToken))
|
|
agt := agenttest.New(t, userClient.URL, authToken, func(o *agent.Options) {
|
|
o.Client = agentClient
|
|
})
|
|
|
|
coderdtest.NewWorkspaceAgentWaiter(t, userClient, workspace.ID).
|
|
WaitFor(coderdtest.AgentsReady)
|
|
|
|
if !setupOpts.skipInitialAppStatus {
|
|
// Report the task app as idle so that waitForTaskIdle can proceed.
|
|
err = agentClient.PatchAppStatus(ctx, agentsdk.PatchAppStatus{
|
|
AppSlug: "task-sidebar",
|
|
State: codersdk.WorkspaceAppStatusStateIdle,
|
|
Message: "ready",
|
|
})
|
|
require.NoError(t, err)
|
|
}
|
|
|
|
return setupCLITaskTestResult{
|
|
ownerClient: ownerClient,
|
|
userClient: userClient,
|
|
task: task,
|
|
agentToken: authToken,
|
|
agent: agt,
|
|
}
|
|
}
|
|
|
|
// pauseTask pauses the task and waits for the stop build to complete.
|
|
func pauseTask(ctx context.Context, t *testing.T, client *codersdk.Client, task codersdk.Task) {
|
|
t.Helper()
|
|
|
|
pauseResp, err := client.PauseTask(ctx, task.OwnerName, task.ID)
|
|
require.NoError(t, err)
|
|
require.NotNil(t, pauseResp.WorkspaceBuild)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, pauseResp.WorkspaceBuild.ID)
|
|
}
|
|
|
|
// resumeTask resumes the task waits for the start build to complete. The task
|
|
// will be in "initializing" state after this returns because no agent is connected.
|
|
func resumeTask(ctx context.Context, t *testing.T, client *codersdk.Client, task codersdk.Task) {
|
|
t.Helper()
|
|
|
|
resumeResp, err := client.ResumeTask(ctx, task.OwnerName, task.ID)
|
|
require.NoError(t, err)
|
|
require.NotNil(t, resumeResp.WorkspaceBuild)
|
|
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, resumeResp.WorkspaceBuild.ID)
|
|
}
|
|
|
|
// setupCLITaskTestWithSnapshot creates a task in the specified status with a log snapshot.
|
|
// Note: We do not use IncludeProvisionerDaemon because these tests use dbfake to directly
|
|
// set up database state and don't need actual provisioning. This also avoids potential
|
|
// interference from the provisioner daemon polling for jobs.
|
|
func setupCLITaskTestWithSnapshot(ctx context.Context, t *testing.T, status codersdk.TaskStatus, messages []agentapisdk.Message) (*codersdk.Client, codersdk.Task) {
|
|
t.Helper()
|
|
|
|
ownerClient, db := coderdtest.NewWithDatabase(t, nil)
|
|
owner := coderdtest.CreateFirstUser(t, ownerClient)
|
|
userClient, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
|
|
|
|
ownerUser, err := ownerClient.User(ctx, owner.UserID.String())
|
|
require.NoError(t, err)
|
|
ownerSubject := coderdtest.AuthzUserSubject(ownerUser)
|
|
|
|
task := createTaskInStatus(t, db, owner.OrganizationID, user.ID, status)
|
|
|
|
// Create snapshot envelope with agentapi format.
|
|
envelope := coderd.TaskLogSnapshotEnvelope{
|
|
Format: "agentapi",
|
|
Data: agentapisdk.GetMessagesResponse{
|
|
Messages: messages,
|
|
},
|
|
}
|
|
snapshotJSON, err := json.Marshal(envelope)
|
|
require.NoError(t, err)
|
|
|
|
// Insert snapshot into database.
|
|
snapshotTime := time.Now()
|
|
err = db.UpsertTaskSnapshot(dbauthz.As(ctx, ownerSubject), database.UpsertTaskSnapshotParams{
|
|
TaskID: task.ID,
|
|
LogSnapshot: json.RawMessage(snapshotJSON),
|
|
LogSnapshotCreatedAt: snapshotTime,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
return userClient, task
|
|
}
|
|
|
|
// setupCLITaskTestWithoutSnapshot creates a task in the specified status without a log snapshot.
|
|
// Note: We do not use IncludeProvisionerDaemon because these tests use dbfake to directly
|
|
// set up database state and don't need actual provisioning. This also avoids potential
|
|
// interference from the provisioner daemon polling for jobs.
|
|
func setupCLITaskTestWithoutSnapshot(t *testing.T, status codersdk.TaskStatus) (*codersdk.Client, codersdk.Task) {
|
|
t.Helper()
|
|
|
|
ownerClient, db := coderdtest.NewWithDatabase(t, nil)
|
|
owner := coderdtest.CreateFirstUser(t, ownerClient)
|
|
userClient, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
|
|
|
|
task := createTaskInStatus(t, db, owner.OrganizationID, user.ID, status)
|
|
|
|
return userClient, task
|
|
}
|
|
|
|
// createTaskInStatus creates a task in the specified status using dbfake.
|
|
func createTaskInStatus(t *testing.T, db database.Store, orgID, ownerID uuid.UUID, status codersdk.TaskStatus) codersdk.Task {
|
|
t.Helper()
|
|
|
|
builder := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
|
|
OrganizationID: orgID,
|
|
OwnerID: ownerID,
|
|
}).
|
|
WithTask(database.TaskTable{
|
|
OrganizationID: orgID,
|
|
OwnerID: ownerID,
|
|
}, nil)
|
|
|
|
switch status {
|
|
case codersdk.TaskStatusPending:
|
|
builder = builder.Pending()
|
|
case codersdk.TaskStatusInitializing:
|
|
builder = builder.Starting()
|
|
case codersdk.TaskStatusPaused:
|
|
builder = builder.Seed(database.WorkspaceBuild{
|
|
Transition: database.WorkspaceTransitionStop,
|
|
})
|
|
default:
|
|
require.Fail(t, "unsupported task status in test helper", "status: %s", status)
|
|
}
|
|
|
|
resp := builder.Do()
|
|
|
|
return codersdk.Task{
|
|
ID: resp.Task.ID,
|
|
Name: resp.Task.Name,
|
|
OrganizationID: resp.Task.OrganizationID,
|
|
OwnerID: resp.Task.OwnerID,
|
|
WorkspaceID: resp.Task.WorkspaceID,
|
|
Status: status,
|
|
}
|
|
}
|
|
|
|
// createAITaskTemplate creates a template configured for AI tasks with a sidebar app.
|
|
func createAITaskTemplate(t *testing.T, client *codersdk.Client, orgID uuid.UUID, opts ...aiTemplateOpt) codersdk.Template {
|
|
t.Helper()
|
|
|
|
opt := aiTemplateOpts{
|
|
authToken: uuid.NewString(),
|
|
}
|
|
for _, o := range opts {
|
|
o(&opt)
|
|
}
|
|
|
|
taskAppID := uuid.New()
|
|
version := coderdtest.CreateTemplateVersion(t, client, orgID, &echo.Responses{
|
|
Parse: echo.ParseComplete,
|
|
ProvisionGraph: []*proto.Response{
|
|
{
|
|
Type: &proto.Response_Graph{
|
|
Graph: &proto.GraphComplete{
|
|
Resources: []*proto.Resource{
|
|
{
|
|
Name: "example",
|
|
Type: "aws_instance",
|
|
Agents: []*proto.Agent{
|
|
{
|
|
Id: uuid.NewString(),
|
|
Name: "example",
|
|
Auth: &proto.Agent_Token{
|
|
Token: opt.authToken,
|
|
},
|
|
Apps: []*proto.App{
|
|
{
|
|
Id: taskAppID.String(),
|
|
Slug: "task-sidebar",
|
|
DisplayName: "Task Sidebar",
|
|
Url: opt.appURL,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
HasAiTasks: true,
|
|
AiTasks: []*proto.AITask{
|
|
{
|
|
AppId: taskAppID.String(),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
|
template := coderdtest.CreateTemplate(t, client, orgID, version.ID)
|
|
|
|
return template
|
|
}
|
|
|
|
// fakeAgentAPI implements a fake AgentAPI HTTP server for testing.
|
|
type fakeAgentAPI struct {
|
|
t *testing.T
|
|
server *httptest.Server
|
|
handlers map[string]http.HandlerFunc
|
|
called map[string]bool
|
|
mu sync.Mutex
|
|
}
|
|
|
|
// startFakeAgentAPI starts an HTTP server that implements the AgentAPI endpoints.
|
|
// handlers is a map of path -> handler function.
|
|
func startFakeAgentAPI(t *testing.T, handlers map[string]http.HandlerFunc) *fakeAgentAPI {
|
|
t.Helper()
|
|
|
|
fake := &fakeAgentAPI{
|
|
t: t,
|
|
handlers: handlers,
|
|
called: make(map[string]bool),
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
// requestDetail records method, path, User-Agent, and a bounded view of
|
|
// the request body so unexpected traffic can be attributed without
|
|
// unbounded logging.
|
|
requestDetail := func(r *http.Request) string {
|
|
body, _ := io.ReadAll(io.LimitReader(r.Body, 4<<10))
|
|
return fmt.Sprintf("method=%s path=%s user-agent=%q body=%q", r.Method, r.URL.Path, r.UserAgent(), body)
|
|
}
|
|
|
|
// Register all provided handlers with call tracking
|
|
for path, handler := range handlers {
|
|
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
|
fake.mu.Lock()
|
|
fake.called[path] = true
|
|
fake.mu.Unlock()
|
|
handler(w, r)
|
|
})
|
|
}
|
|
|
|
// Known agentapi endpoints without a handler fail the test: a coderd
|
|
// regression that calls an endpoint the test did not stub must be
|
|
// caught. The 404 also gives the client a well-formed response instead
|
|
// of leaving it hanging.
|
|
knownEndpoints := []string{"/status", "/messages", "/message"}
|
|
for _, endpoint := range knownEndpoints {
|
|
if handlers[endpoint] == nil {
|
|
endpoint := endpoint // capture loop variable
|
|
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
|
|
t.Errorf("unexpected call to agentapi endpoint %s with no handler defined: %s", endpoint, requestDetail(r))
|
|
w.WriteHeader(http.StatusNotFound)
|
|
})
|
|
}
|
|
}
|
|
// Unknown paths get a 404 and a log line, but do not fail the test.
|
|
// Stray traffic can arrive here, most likely from another test's
|
|
// lingering client whose closed server's ephemeral port was reused by
|
|
// this one, so failing on unknown paths would create false flakes.
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
t.Logf("unexpected request to unknown path, likely cross-test chatter from a reused ephemeral port: %s", requestDetail(r))
|
|
w.WriteHeader(http.StatusNotFound)
|
|
})
|
|
|
|
fake.server = httptest.NewServer(mux)
|
|
|
|
// Register cleanup to check that all defined handlers were called
|
|
t.Cleanup(func() {
|
|
fake.server.Close()
|
|
fake.mu.Lock()
|
|
for path := range handlers {
|
|
if !fake.called[path] {
|
|
t.Errorf("handler for %s was defined but never called", path)
|
|
}
|
|
}
|
|
})
|
|
return fake
|
|
}
|
|
|
|
func (f *fakeAgentAPI) URL() string {
|
|
return f.server.URL
|
|
}
|
|
|
|
type aiTemplateOpts struct {
|
|
appURL string
|
|
authToken string
|
|
}
|
|
|
|
type aiTemplateOpt func(*aiTemplateOpts)
|
|
|
|
func withSidebarURL(url string) aiTemplateOpt {
|
|
return func(o *aiTemplateOpts) { o.appURL = url }
|
|
}
|
|
|
|
func withAgentToken(token string) aiTemplateOpt {
|
|
return func(o *aiTemplateOpts) { o.authToken = token }
|
|
}
|