MCPcopy Index your code
hub / github.com/coder/coder / getWorkspaceConn

Method getWorkspaceConn

coderd/x/chatd/chatd.go:1063–1237  ·  view source on GitHub ↗
(ctx context.Context)

Source from the content-addressed store, hash-verified

1061}
1062
1063func (c *turnWorkspaceContext) getWorkspaceConn(ctx context.Context) (workspacesdk.AgentConn, error) {
1064 if c.server.agentConnFn == nil {
1065 return nil, xerrors.New("workspace agent connector is not configured")
1066 }
1067
1068 for attempt := 0; attempt < 2; attempt++ {
1069 c.mu.Lock()
1070 currentConn, staleRelease := c.getWorkspaceConnLocked()
1071 // Capture agentID in the same lock section as
1072 // currentConn to prevent a TOCTOU race with
1073 // concurrent clearCachedWorkspaceState calls.
1074 agentID := c.agent.ID
1075 c.mu.Unlock()
1076
1077 // Status check on cache hit: re-fetch the agent
1078 // row so we see the latest heartbeat rather than
1079 // a potentially stale cached copy.
1080 if currentConn != nil {
1081 if agentID != uuid.Nil {
1082 freshAgent, err := c.server.db.GetWorkspaceAgentByID(ctx, agentID)
1083 if err != nil {
1084 c.server.logger.Warn(ctx, "failed to re-fetch agent for status check",
1085 slog.F("agent_id", agentID),
1086 slog.Error(err),
1087 )
1088 // On DB error the check re-runs on the
1089 // next tool call.
1090 } else if _, disconnected := agentDisconnectedFor(
1091 c.server.clock.Now(),
1092 freshAgent,
1093 c.server.agentInactiveDisconnectTimeout,
1094 ); disconnected {
1095 c.clearCachedWorkspaceState()
1096 continue
1097 }
1098 }
1099 return currentConn, nil
1100 }
1101 if staleRelease != nil {
1102 staleRelease()
1103 }
1104
1105 chatSnapshot, agent, err := c.ensureWorkspaceAgent(ctx)
1106 if err != nil {
1107 return nil, err
1108 }
1109 if err := c.externalAgentPreflightError(ctx, chatSnapshot, agent); err != nil {
1110 return nil, err
1111 }
1112
1113 // Wrap the dial in a timeout to bound the time spent
1114 // waiting for an unreachable agent. The timeout scopes
1115 // only dialWithLazyValidation, not ensureWorkspaceAgent
1116 // or the post-dial binding steps.
1117 dialCtx, dialCancel := context.WithTimeoutCause(ctx, c.server.dialTimeout, errChatDialTimeout)
1118 dialResult, err := dialWithLazyValidation(
1119 dialCtx,
1120 agent.ID,

Calls 15

ensureWorkspaceAgentMethod · 0.95
externalAgentErrorMethod · 0.95
agentDisconnectedForFunction · 0.85
dialWithLazyValidationFunction · 0.85
DialFuncFuncType · 0.85