`message_agent` no longer takes an `interrupt` flag, and always steers. If the child is busy, it gets the message before its next model call and keeps working. To correct or redirect a busy child, the parent just calls `message_agent`, and `interrupt_agent` only stops it, which is the same split the API has after #31174. The tool result also drops `interrupted`, as it was just whether the child was running before the send. That was the last caller of the interrupt busy behaviour, so chatd and chatstate drop it too. `SendMessage` never interrupts now. On a busy chat it only ever adds the message to a lane, so the sends that moved a running chat to interrupting, or a `requires_action` chat back to running, are gone, along with the send's inline interruption finish for chats with no worker. Most of the diff is deleted tests. A steer send to a paused chat, or to an errored chat whose next message is being edited, no longer fails with a 429 at the queue limit when it's delivered straight away, which is whenever the message being edited is a queue message. Part of CODAGT-1140
691 lines
22 KiB
Go
691 lines
22 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/sqlc-dev/pqtype"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
dbpubsub "github.com/coder/coder/v2/coderd/database/pubsub"
|
|
coderdpubsub "github.com/coder/coder/v2/coderd/pubsub"
|
|
"github.com/coder/coder/v2/coderd/x/agenthooks/dispatch"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chathooks"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
|
"github.com/coder/coder/v2/codersdk/x/agenthooks"
|
|
)
|
|
|
|
type subagentAwaitOutcome struct {
|
|
chat database.Chat
|
|
report string
|
|
recording recordingResult
|
|
// When timedOut is true, report and recording are unset.
|
|
timedOut bool
|
|
}
|
|
|
|
func (p *Server) awaitSubagent(
|
|
ctx context.Context,
|
|
parent database.Chat,
|
|
targetChatID uuid.UUID,
|
|
timeout time.Duration,
|
|
) (subagentAwaitOutcome, error) {
|
|
isDescendant, err := isSubagentDescendant(ctx, p.db, parent.ID, targetChatID)
|
|
if err != nil {
|
|
return subagentAwaitOutcome{}, xerrors.Errorf("failed to verify subagent relationship: %v", err)
|
|
}
|
|
if !isDescendant {
|
|
return subagentAwaitOutcome{}, ErrSubagentNotDescendant
|
|
}
|
|
|
|
// Recording a computer_use child is best-effort and never blocks the wait.
|
|
var recordingID string
|
|
var agentConn workspacesdk.AgentConn
|
|
if target := p.subagentTargetChatInfo(ctx, targetChatID, "recording"); target != nil && target.Mode.Valid && target.Mode.ChatMode == database.ChatModeComputerUse && target.AgentID.Valid && p.agentConnFn != nil {
|
|
conn, closeFn, connErr := p.agentConnFn(ctx, target.AgentID.UUID)
|
|
if connErr == nil {
|
|
agentConn = conn
|
|
defer closeFn()
|
|
recordingID = targetChatID.String()
|
|
if startErr := conn.StartDesktopRecording(ctx, workspacesdk.StartDesktopRecordingRequest{RecordingID: recordingID}); startErr != nil {
|
|
p.logger.Warn(ctx, "failed to start desktop recording", slog.Error(startErr))
|
|
recordingID = ""
|
|
}
|
|
} else {
|
|
p.logger.Warn(ctx, "failed to get agent conn for recording", slog.Error(connErr))
|
|
}
|
|
}
|
|
|
|
// On timeout or error, leave the recording running on the agent so
|
|
// the next wait continues it. Only success stops and stores it.
|
|
targetChat, report, err := p.awaitSubagentCompletion(ctx, parent.ID, targetChatID, timeout)
|
|
if xerrors.Is(err, ErrSubagentWaitTimeout) {
|
|
// The agent may have completed between the last poll and the
|
|
// timer firing, so re-check with a fresh read before reporting
|
|
// a timeout.
|
|
checkedChat, checkedReport, done, checkErr := p.checkSubagentCompletion(ctx, targetChatID)
|
|
if checkErr != nil {
|
|
return subagentAwaitOutcome{}, checkErr
|
|
}
|
|
if !done {
|
|
return subagentAwaitOutcome{chat: checkedChat, timedOut: true}, nil
|
|
}
|
|
targetChat, report, err = handleSubagentDone(checkedChat, checkedReport)
|
|
}
|
|
if err != nil {
|
|
return subagentAwaitOutcome{}, err
|
|
}
|
|
outcome := subagentAwaitOutcome{chat: targetChat, report: report}
|
|
if recordingID != "" && agentConn != nil {
|
|
// Use a fresh context for cleanup so a canceled parent context
|
|
// does not prevent recording storage.
|
|
stopCtx, stopCancel := context.WithTimeout(context.WithoutCancel(ctx), subagentRecordingStopTimeout)
|
|
defer stopCancel()
|
|
outcome.recording = p.stopAndStoreRecording(stopCtx, agentConn,
|
|
recordingID, parent.ID, parent.OwnerID, parent.WorkspaceID)
|
|
}
|
|
return outcome, nil
|
|
}
|
|
|
|
func (p *Server) sendSubagentMessage(
|
|
ctx context.Context,
|
|
parentChatID uuid.UUID,
|
|
targetChatID uuid.UUID,
|
|
message string,
|
|
) (database.Chat, error) {
|
|
message = strings.TrimSpace(message)
|
|
if message == "" {
|
|
return database.Chat{}, xerrors.New("message is required")
|
|
}
|
|
|
|
isDescendant, err := isSubagentDescendant(ctx, p.db, parentChatID, targetChatID)
|
|
if err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
if !isDescendant {
|
|
return database.Chat{}, ErrSubagentNotDescendant
|
|
}
|
|
|
|
// Look up the target chat to get the owner for CreatedBy.
|
|
targetChat, err := p.db.GetChatByID(ctx, targetChatID)
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("get target chat: %w", err)
|
|
}
|
|
|
|
sendResult, err := p.SendMessage(ctx, SendMessageOptions{
|
|
ChatID: targetChatID,
|
|
CreatedBy: targetChat.OwnerID,
|
|
Content: []codersdk.ChatMessagePart{codersdk.ChatMessageText(message)},
|
|
BusyBehavior: SendMessageBusyBehaviorSteer,
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
|
|
return sendResult.Chat, nil
|
|
}
|
|
|
|
func (p *Server) interruptSubagent(
|
|
ctx context.Context,
|
|
parentChatID uuid.UUID,
|
|
targetChatID uuid.UUID,
|
|
) (database.Chat, bool, error) {
|
|
isDescendant, err := isSubagentDescendant(ctx, p.db, parentChatID, targetChatID)
|
|
if err != nil {
|
|
return database.Chat{}, false, err
|
|
}
|
|
if !isDescendant {
|
|
return database.Chat{}, false, ErrSubagentNotDescendant
|
|
}
|
|
|
|
targetChat, err := p.db.GetChatByID(ctx, targetChatID)
|
|
if err != nil {
|
|
return database.Chat{}, false, xerrors.Errorf("get target chat: %w", err)
|
|
}
|
|
|
|
updatedChat, interrupted, err := p.InterruptChat(ctx, targetChat)
|
|
if err != nil {
|
|
return database.Chat{}, false, xerrors.Errorf("interrupt subagent chat: %w", err)
|
|
}
|
|
return updatedChat, interrupted, nil
|
|
}
|
|
|
|
func (p *Server) listSubagents(ctx context.Context, parentChatID uuid.UUID) ([]database.Chat, error) {
|
|
rows, err := p.db.GetChildChatsByParentIDs(ctx, database.GetChildChatsByParentIDsParams{
|
|
ParentIds: []uuid.UUID{parentChatID},
|
|
// Exclude archived children. An invalid NullBool would include
|
|
// archived rows.
|
|
Archived: sql.NullBool{Bool: false, Valid: true},
|
|
})
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("list child agents: %w", err)
|
|
}
|
|
children := make([]database.Chat, 0, len(rows))
|
|
for _, row := range rows {
|
|
children = append(children, row.Chat)
|
|
}
|
|
slices.SortStableFunc(children, func(a, b database.Chat) int {
|
|
if c := b.UpdatedAt.Compare(a.UpdatedAt); c != 0 {
|
|
return c
|
|
}
|
|
return strings.Compare(b.ID.String(), a.ID.String())
|
|
})
|
|
return children, nil
|
|
}
|
|
|
|
func (p *Server) subagentTargetChatInfo(ctx context.Context, chatID uuid.UUID, operation string) *database.Chat {
|
|
chat, err := p.db.GetChatByID(ctx, chatID)
|
|
if err == nil {
|
|
return &chat
|
|
}
|
|
if !xerrors.Is(err, sql.ErrNoRows) {
|
|
p.logger.Warn(ctx, "unexpected error looking up chat for "+operation, slog.F("chat_id", chatID), slog.Error(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Server) loadSubagentSpawnParentChat(
|
|
ctx context.Context,
|
|
currentChat func() database.Chat,
|
|
) (database.Chat, error) {
|
|
parent := currentChat()
|
|
if err := validateSubagentSpawnParent(parent); err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
reloadedParent, err := p.db.GetChatByID(ctx, parent.ID)
|
|
if err != nil {
|
|
p.logger.Warn(ctx, "failed to load parent chat for spawn_agent",
|
|
slog.F("chat_id", parent.ID),
|
|
slog.Error(err),
|
|
)
|
|
return database.Chat{}, xerrors.New("failed to load parent chat")
|
|
}
|
|
parent = reloadedParent
|
|
if err := validateSubagentSpawnParent(parent); err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
// Fail before prompt hooks run for a child that cannot be created.
|
|
// Spawn parents are always roots, so this is the family's archived
|
|
// flag. The locked check in chatstate.CreateChat stays authoritative.
|
|
if parent.Archived {
|
|
return database.Chat{}, errSpawnUnderArchivedParent(chatstate.ErrChatFamilyArchived)
|
|
}
|
|
return parent, nil
|
|
}
|
|
|
|
// errSpawnUnderArchivedParent wraps err, which must match
|
|
// chatstate.ErrChatFamilyArchived, into the tool error spawn_agent
|
|
// returns to the model.
|
|
func errSpawnUnderArchivedParent(err error) error {
|
|
return xerrors.Errorf("cannot create a child agent because the parent chat is archived: %w", err)
|
|
}
|
|
|
|
// childSubagentChatOptions carries per-child overrides for subagent chat
|
|
// creation. modelConfigIDOverride, reasoningEffortOverride, and
|
|
// planModeOverride apply to any subagent. inheritedMCPServerIDs is an
|
|
// Explore-only snapshot of the spawning parent turn's effective external MCP
|
|
// entitlement. resolveExploreToolSnapshot computes and persists it on the
|
|
// child chat. Non-Explore children ignore this field.
|
|
type childSubagentChatOptions struct {
|
|
chatMode database.NullChatMode
|
|
systemPrompt string
|
|
modelConfigIDOverride *uuid.UUID
|
|
reasoningEffortOverride *string
|
|
planModeOverride *database.NullChatPlanMode
|
|
inheritedMCPServerIDs []uuid.UUID
|
|
}
|
|
|
|
// resolveExploreToolSnapshot computes the child chat's inherited MCP
|
|
// server snapshot from the spawning parent turn.
|
|
//
|
|
// The MCP set is filtered in two stages. First,
|
|
// filterExternalMCPConfigsForTurn applies the parent turn's plan-mode
|
|
// policy to the parent's MCP configs, producing visibleConfigs. Second,
|
|
// if the parent is itself an Explore child, the visible set is narrowed to
|
|
// the parent's persisted MCPServerIDs so an Explore chain cannot
|
|
// re-escalate beyond the original grant. Non-Explore parents pass
|
|
// through the second stage unchanged.
|
|
func (p *Server) resolveExploreToolSnapshot(
|
|
ctx context.Context,
|
|
parent database.Chat,
|
|
) ([]uuid.UUID, error) {
|
|
inheritedMCPServerIDs := []uuid.UUID{}
|
|
if len(parent.MCPServerIDs) > 0 {
|
|
configs, err := enabledMCPServerConfigsForChatOrg(ctx, p.db, parent.OrganizationID, parent.MCPServerIDs)
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("get parent MCP server configs for chat %s: %w", parent.ID, err)
|
|
}
|
|
|
|
visibleConfigs, _ := filterExternalMCPConfigsForTurn(
|
|
configs,
|
|
parent.PlanMode,
|
|
parent.ParentChatID,
|
|
)
|
|
// Empty means the parent is not Explore, so all plan-filtered
|
|
// configs remain eligible. Populated means the parent is
|
|
// Explore, so only its persisted snapshot can pass.
|
|
allowedParentIDs := map[uuid.UUID]struct{}{}
|
|
if isExploreSubagentMode(parent.Mode) {
|
|
for _, id := range parent.MCPServerIDs {
|
|
allowedParentIDs[id] = struct{}{}
|
|
}
|
|
}
|
|
for _, cfg := range visibleConfigs {
|
|
if len(allowedParentIDs) > 0 {
|
|
if _, ok := allowedParentIDs[cfg.ID]; !ok {
|
|
continue
|
|
}
|
|
}
|
|
inheritedMCPServerIDs = append(inheritedMCPServerIDs, cfg.ID)
|
|
}
|
|
}
|
|
|
|
return inheritedMCPServerIDs, nil
|
|
}
|
|
|
|
func (p *Server) createChildSubagentChatWithOptions(
|
|
ctx context.Context,
|
|
parent database.Chat,
|
|
prompt string,
|
|
title string,
|
|
opts childSubagentChatOptions,
|
|
) (database.Chat, error) {
|
|
if parent.ParentChatID.Valid {
|
|
return database.Chat{}, xerrors.New("delegated chats cannot create child subagents")
|
|
}
|
|
|
|
prompt = strings.TrimSpace(prompt)
|
|
if prompt == "" {
|
|
return database.Chat{}, xerrors.New("prompt is required")
|
|
}
|
|
|
|
title = strings.TrimSpace(title)
|
|
|
|
rootChatID := parent.ID
|
|
if parent.RootChatID.Valid {
|
|
rootChatID = parent.RootChatID.UUID
|
|
}
|
|
|
|
modelConfigID := parent.LastModelConfigID
|
|
if opts.modelConfigIDOverride != nil {
|
|
modelConfigID = *opts.modelConfigIDOverride
|
|
}
|
|
if modelConfigID == uuid.Nil {
|
|
return database.Chat{}, xerrors.New("model config is required")
|
|
}
|
|
childPlanMode := parent.PlanMode
|
|
if opts.planModeOverride != nil {
|
|
childPlanMode = *opts.planModeOverride
|
|
}
|
|
|
|
mcpServerIDs := parent.MCPServerIDs
|
|
if isExploreSubagentMode(opts.chatMode) {
|
|
mcpServerIDs = slices.Clone(opts.inheritedMCPServerIDs)
|
|
}
|
|
if mcpServerIDs == nil {
|
|
mcpServerIDs = []uuid.UUID{}
|
|
}
|
|
|
|
labelsJSON, err := json.Marshal(database.StringMap{})
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("marshal labels: %w", err)
|
|
}
|
|
childSystemPrompt := codersdk.SanitizePromptText(opts.systemPrompt)
|
|
// Resolve the deployment prompt before opening the transaction so
|
|
// child chat creation does not hold one DB connection while waiting
|
|
// for another pool checkout.
|
|
deploymentPrompt, err := p.resolveDeploymentSystemPrompt(ctx)
|
|
if err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
// Delegated chats cannot call list_agents or message_agent, so
|
|
// strip the root-only orchestration guidance from their prompt.
|
|
deploymentPrompt = strings.Replace(deploymentPrompt, subagentOrchestrationPromptBlock, "", 1)
|
|
organizationPrompt, err := p.resolveOrganizationSystemPrompt(ctx, parent.OrganizationID)
|
|
if err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
|
|
// Review before persistence so spawned chats cannot bypass prompt policy.
|
|
childChatID := uuid.New()
|
|
var promptResult *chathooks.Result
|
|
if p.hooks.Enabled() {
|
|
mintedTurnID := uuid.New()
|
|
promptMessage, err := chathooks.UserPromptMessage([]codersdk.ChatMessagePart{codersdk.ChatMessageText(prompt)})
|
|
if err != nil {
|
|
return database.Chat{}, err
|
|
}
|
|
promptResult, err = p.hooks.Trigger(ctx, chathooks.Chat{
|
|
ID: childChatID,
|
|
OwnerID: parent.OwnerID,
|
|
WorkspaceID: parent.WorkspaceID,
|
|
ParentChatID: uuid.NullUUID{UUID: parent.ID, Valid: true},
|
|
RootChatID: uuid.NullUUID{UUID: rootChatID, Valid: true},
|
|
TurnID: &mintedTurnID,
|
|
}, promptMessage, agenthooks.EventUserPromptSubmit, dispatch.CapacityClassGeneration)
|
|
if err != nil {
|
|
return database.Chat{}, chathooks.UserPromptDenial(err)
|
|
}
|
|
override, overridden, overrideErr := chathooks.UserPromptOverride(promptResult)
|
|
if overrideErr != nil {
|
|
return database.Chat{}, overrideErr
|
|
}
|
|
if overridden {
|
|
// The overridden prompt also feeds the fallback title below.
|
|
prompt = override
|
|
}
|
|
}
|
|
titleSource := database.ChatTitleSourceUser
|
|
if title == "" {
|
|
title = chatprompt.FallbackTitle(prompt)
|
|
titleSource = database.ChatTitleSourceFallback
|
|
}
|
|
|
|
workspaceAwareness := workspaceDetachedNoCreateAwareness
|
|
if parent.WorkspaceID.Valid {
|
|
workspaceAwareness = workspaceAttachedAwareness
|
|
}
|
|
workspaceAwarenessContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(workspaceAwareness),
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("marshal workspace awareness: %w", err)
|
|
}
|
|
childUserParts := []codersdk.ChatMessagePart{codersdk.ChatMessageText(prompt)}
|
|
childUserParts = append(childUserParts, chathooks.UserPromptParts(promptResult)...)
|
|
userContent, err := chatprompt.MarshalParts(childUserParts)
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("marshal initial user content: %w", err)
|
|
}
|
|
|
|
initialMessages := make([]chatstate.Message, 0, 5)
|
|
if deploymentPrompt != "" {
|
|
deploymentContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(deploymentPrompt),
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("marshal deployment system prompt: %w", err)
|
|
}
|
|
initialMessages = append(initialMessages, systemMessage(deploymentContent, modelConfigID))
|
|
}
|
|
if organizationPrompt != "" {
|
|
organizationContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(organizationPrompt),
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("marshal organization system prompt: %w", err)
|
|
}
|
|
initialMessages = append(initialMessages, systemMessage(organizationContent, modelConfigID))
|
|
}
|
|
if childSystemPrompt != "" {
|
|
childSystemPromptContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText(childSystemPrompt),
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, xerrors.Errorf("marshal child system prompt: %w", err)
|
|
}
|
|
initialMessages = append(initialMessages, systemMessage(childSystemPromptContent, modelConfigID))
|
|
}
|
|
initialMessages = append(initialMessages, systemMessage(workspaceAwarenessContent, modelConfigID))
|
|
|
|
// The child shares the parent's workspace and agent, so it inherits
|
|
// workspace context the same way a top-level chat does: pinned from the
|
|
// agent's latest snapshot (see hydrateChatContextOnCreate below). The
|
|
// parent's context is not copied into child history.
|
|
initialMessages = append(initialMessages, userMessage(userContent, modelConfigID, parent.OwnerID, opts.reasoningEffortOverride))
|
|
|
|
publisher := p.pubsub
|
|
if publisher == nil {
|
|
publisher = dbpubsub.NewInMemory()
|
|
}
|
|
result, err := chatstate.CreateChatWithID(ctx, p.db, publisher, childChatID, chatstate.CreateChatInput{
|
|
OrganizationID: parent.OrganizationID,
|
|
OwnerID: parent.OwnerID,
|
|
WorkspaceID: parent.WorkspaceID,
|
|
BuildID: parent.BuildID,
|
|
AgentID: parent.AgentID,
|
|
ParentChatID: uuid.NullUUID{UUID: parent.ID, Valid: true},
|
|
RootChatID: uuid.NullUUID{UUID: rootChatID, Valid: true},
|
|
LastModelConfigID: modelConfigID,
|
|
Title: title,
|
|
TitleSource: titleSource,
|
|
Mode: opts.chatMode,
|
|
PlanMode: childPlanMode,
|
|
MCPServerIDs: mcpServerIDs,
|
|
Labels: pqtype.NullRawMessage{
|
|
RawMessage: labelsJSON,
|
|
Valid: true,
|
|
},
|
|
DynamicTools: pqtype.NullRawMessage{},
|
|
ClientType: parent.ClientType,
|
|
InitialMessages: initialMessages,
|
|
InitialStatus: database.ChatStatusRunning,
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, chatstate.ErrChatFamilyArchived) {
|
|
return database.Chat{}, errSpawnUnderArchivedParent(err)
|
|
}
|
|
return database.Chat{}, xerrors.Errorf("create child chat: %w", err)
|
|
}
|
|
|
|
child := result.Chat
|
|
|
|
// Pin the child to its agent's latest context snapshot, mirroring the
|
|
// top-level create path. The child shares the parent's workspace agent,
|
|
// so this reproduces the parent's workspace context without copying it
|
|
// through chat history.
|
|
p.hydrateChatContextOnCreate(ctx, child)
|
|
|
|
p.publishChatPubsubEvent(child, codersdk.ChatWatchEventKindCreated, nil)
|
|
return child, nil
|
|
}
|
|
|
|
func (p *Server) awaitSubagentCompletion(
|
|
ctx context.Context,
|
|
parentChatID uuid.UUID,
|
|
targetChatID uuid.UUID,
|
|
timeout time.Duration,
|
|
) (database.Chat, string, error) {
|
|
isDescendant, err := isSubagentDescendant(ctx, p.db, parentChatID, targetChatID)
|
|
if err != nil {
|
|
return database.Chat{}, "", err
|
|
}
|
|
if !isDescendant {
|
|
return database.Chat{}, "", ErrSubagentNotDescendant
|
|
}
|
|
|
|
// Check immediately before entering the poll loop.
|
|
targetChat, report, done, checkErr := p.checkSubagentCompletion(ctx, targetChatID)
|
|
if checkErr != nil {
|
|
return database.Chat{}, "", checkErr
|
|
}
|
|
if done {
|
|
return handleSubagentDone(targetChat, report)
|
|
}
|
|
|
|
if timeout <= 0 {
|
|
timeout = defaultSubagentWaitTimeout
|
|
}
|
|
timer := p.clock.NewTimer(timeout, "chatd", "subagent_await")
|
|
defer timer.Stop()
|
|
|
|
// Subscribe for fast status notifications and use a less
|
|
// aggressive fallback poll. If subscription fails, fall back to
|
|
// the original 200ms polling.
|
|
pollInterval := subagentAwaitFallbackPoll
|
|
ch := make(chan struct{}, 1)
|
|
notifyCh := (<-chan struct{})(ch)
|
|
cancel, subErr := p.pubsub.SubscribeWithErr(
|
|
coderdpubsub.ChatStateUpdateChannel(targetChatID),
|
|
func(_ context.Context, _ []byte, _ error) {
|
|
// Non-blocking send so we never stall the
|
|
// pubsub dispatch goroutine.
|
|
select {
|
|
case ch <- struct{}{}:
|
|
default:
|
|
}
|
|
},
|
|
)
|
|
if subErr == nil {
|
|
defer cancel()
|
|
} else {
|
|
// Subscription failed; fall back to fast polling.
|
|
pollInterval = subagentAwaitPollInterval
|
|
notifyCh = nil
|
|
}
|
|
|
|
ticker := p.clock.NewTicker(pollInterval, "chatd", "subagent_poll")
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-notifyCh:
|
|
case <-ticker.C:
|
|
case <-timer.C:
|
|
return database.Chat{}, "", ErrSubagentWaitTimeout
|
|
case <-ctx.Done():
|
|
return database.Chat{}, "", ctx.Err()
|
|
}
|
|
|
|
targetChat, report, done, checkErr = p.checkSubagentCompletion(ctx, targetChatID)
|
|
if checkErr != nil {
|
|
return database.Chat{}, "", checkErr
|
|
}
|
|
if done {
|
|
return handleSubagentDone(targetChat, report)
|
|
}
|
|
}
|
|
}
|
|
|
|
// handleSubagentDone translates a completed subagent check into the
|
|
// appropriate return value. An error-status chat is returned as a typed
|
|
// subagentStatusError that carries the chat and report so the
|
|
// wait_agent handler can surface a structured, recoverable-aware payload.
|
|
func handleSubagentDone(
|
|
chat database.Chat,
|
|
report string,
|
|
) (database.Chat, string, error) {
|
|
if chat.Status == database.ChatStatusError {
|
|
reason := strings.TrimSpace(report)
|
|
if reason == "" {
|
|
reason = "agent reached error status"
|
|
}
|
|
return database.Chat{}, "", &subagentStatusError{
|
|
chat: chat,
|
|
report: report,
|
|
reason: reason,
|
|
}
|
|
}
|
|
return chat, report, nil
|
|
}
|
|
|
|
func (p *Server) checkSubagentCompletion(
|
|
ctx context.Context,
|
|
chatID uuid.UUID,
|
|
) (database.Chat, string, bool, error) {
|
|
chat, err := p.db.GetChatByID(ctx, chatID)
|
|
if err != nil {
|
|
return database.Chat{}, "", false, xerrors.Errorf("get chat: %w", err)
|
|
}
|
|
|
|
// interrupting is transient: the worker transitions it to
|
|
// waiting (no queued messages) or running (queued messages).
|
|
// Treat it as not-done so the agent settles before
|
|
// classification, avoiding stale partial output. Paused is not
|
|
// done either: the child resumes when the queued edit ends.
|
|
if chat.Status == database.ChatStatusRunning ||
|
|
chat.Status == database.ChatStatusInterrupting ||
|
|
chat.Status == database.ChatStatusPaused {
|
|
return chat, "", false, nil
|
|
}
|
|
|
|
report, err := latestSubagentAssistantMessage(ctx, p.db, chatID)
|
|
if err != nil {
|
|
return database.Chat{}, "", false, err
|
|
}
|
|
|
|
return chat, report, true, nil
|
|
}
|
|
|
|
func latestSubagentAssistantMessage(
|
|
ctx context.Context,
|
|
store database.Store,
|
|
chatID uuid.UUID,
|
|
) (string, error) {
|
|
messages, err := store.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: chatID,
|
|
AfterID: 0,
|
|
})
|
|
if err != nil {
|
|
return "", xerrors.Errorf("get chat messages: %w", err)
|
|
}
|
|
|
|
for i := len(messages) - 1; i >= 0; i-- {
|
|
message := messages[i]
|
|
if message.Role != database.ChatMessageRoleAssistant ||
|
|
message.Visibility == database.ChatMessageVisibilityModel {
|
|
continue
|
|
}
|
|
|
|
content, parseErr := chatprompt.ParseContent(message)
|
|
if parseErr != nil {
|
|
continue
|
|
}
|
|
text := strings.TrimSpace(contentBlocksToText(content))
|
|
if text == "" {
|
|
continue
|
|
}
|
|
return text, nil
|
|
}
|
|
|
|
return "", nil
|
|
}
|
|
|
|
// isSubagentDescendant reports whether targetChatID is a descendant
|
|
// of ancestorChatID by walking up the parent chain from the target.
|
|
// This is O(depth) DB queries instead of O(nodes) BFS.
|
|
func isSubagentDescendant(
|
|
ctx context.Context,
|
|
store database.Store,
|
|
ancestorChatID uuid.UUID,
|
|
targetChatID uuid.UUID,
|
|
) (bool, error) {
|
|
if ancestorChatID == targetChatID {
|
|
return false, nil
|
|
}
|
|
|
|
currentID := targetChatID
|
|
visited := map[uuid.UUID]struct{}{} // cycle protection
|
|
for {
|
|
if _, seen := visited[currentID]; seen {
|
|
return false, nil
|
|
}
|
|
visited[currentID] = struct{}{}
|
|
|
|
chat, err := store.GetChatByID(ctx, currentID)
|
|
if err != nil {
|
|
if xerrors.Is(err, sql.ErrNoRows) {
|
|
return false, nil // chain broken; not a confirmed descendant
|
|
}
|
|
return false, xerrors.Errorf("get chat %s: %w", currentID, err)
|
|
}
|
|
if !chat.ParentChatID.Valid {
|
|
return false, nil // reached root without finding ancestor
|
|
}
|
|
if chat.ParentChatID.UUID == ancestorChatID {
|
|
return true, nil
|
|
}
|
|
currentID = chat.ParentChatID.UUID
|
|
}
|
|
}
|