Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RemoteInfo Rpc #1719

Merged
merged 6 commits into from
Jan 12, 2025
Merged

RemoteInfo Rpc #1719

merged 6 commits into from
Jan 12, 2025

Conversation

oneirocosm
Copy link
Member

Adds an Rpc Command for getting RemoteInfo. This is used to replace the session that was used to determine the shell on remote machines.

This adds an rpc command to get info on the remote system.
The SoftQuote function makes it unnecessary to fully expand the home
directory path. This replaces those cases with a ~ instead.
This removes the need to create a new session for detecting the shell
Copy link
Contributor

coderabbitai bot commented Jan 12, 2025

Walkthrough

The pull request introduces a comprehensive set of changes across multiple files, focusing on remote shell information retrieval and connection management. The modifications primarily involve updating the mechanism for obtaining remote shell and system information, removing the ConnName field from RemoteInfo, and introducing a new RPC command remotegetinfo.

Key changes include adding a new method RemoteGetInfoCommand in various components like wshclient, wshremote, and wshclientapi, modifying the GetInfo() function in wshutil to determine shell information more robustly, and updating how connection names are retrieved in server-side components. The changes simplify the process of getting remote system information and remove direct dependencies on connection names in certain contexts, potentially streamlining the remote connection and shell execution workflows.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (5)
pkg/shellexec/shellexec.go (3)

Line range hint 22-32: Organize Import Statements for Readability

Consider grouping related import statements together and removing any unused imports to improve code readability and maintainability. Specifically, verify if all newly added imports are necessary.


292-299: Error Handling Enhancement When Obtaining Remote Info

Currently, if wshclient.RemoteGetInfoCommand fails, the error is returned directly. Provide more context in the error message to aid debugging.

Apply this diff to enhance the error message:

     if err != nil {
-        return nil, fmt.Errorf("unable to obtain client info: %w", err)
+        return nil, fmt.Errorf("failed to retrieve remote shell information: %w", err)
     }

308-309: Redundant Log Message

The log message "using shell: %s" is already being logged in other parts of the code. Ensure that logging is consistent and necessary to avoid cluttering the logs.

Consider removing or consolidating log messages for clarity.

pkg/wshrpc/wshserver/wshserver.go (2)

703-707: LGTM! Good architectural improvement.

The change to extract the connection name from RPC context instead of RemoteInfo aligns with the PR's goal and improves the architecture by:

  1. Maintaining a single source of truth for connection names
  2. Reducing coupling between RemoteInfo and connection management

705-706: Improve error message clarity.

The error message could be more specific about what went wrong.

-		return false, fmt.Errorf("could not determine handler from context")
+		return false, fmt.Errorf("RPC response handler not found in context")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a7771b and a36b5d4.

📒 Files selected for processing (11)
  • cmd/wsh/cmd/wshcmd-connserver.go (1 hunks)
  • frontend/app/store/wshclientapi.ts (1 hunks)
  • frontend/types/gotypes.d.ts (0 hunks)
  • pkg/remote/conncontroller/conncontroller.go (1 hunks)
  • pkg/remote/connutil.go (0 hunks)
  • pkg/shellexec/shellexec.go (4 hunks)
  • pkg/wshrpc/wshclient/wshclient.go (1 hunks)
  • pkg/wshrpc/wshremote/wshremote.go (2 hunks)
  • pkg/wshrpc/wshrpctypes.go (2 hunks)
  • pkg/wshrpc/wshserver/wshserver.go (1 hunks)
  • pkg/wshutil/wshutil.go (3 hunks)
💤 Files with no reviewable changes (2)
  • frontend/types/gotypes.d.ts
  • pkg/remote/connutil.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: CodeQL
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (11)
pkg/shellexec/shellexec.go (2)

324-325: Potential Issue with Fish Shell Initialization

The command constructed for Fish shell may not set the environment variables as intended. Verify that the -C option works correctly in the remote environment.

Run the following script to verify Fish shell initialization commands:

✅ Verification successful

Fish Shell Initialization Verified as Correct

The command construction for Fish shell using -C option and set -x PATH is implemented correctly and consistently across the codebase. The path handling and environment variable setting follow Fish shell conventions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the Fish shell correctly processes the initialization commands.

# Test: Look for Fish shell initialization in the codebase.
rg 'if isFishShell' -A 5

Length of output: 1688


321-322: Ensure Correct Quoting of Bash RC Path

When constructing the bashPath, ensure that genconn.SoftQuote properly handles paths with spaces or special characters, especially in remote environments.

Run the following script to check for any issues with path quoting:

✅ Verification successful

Path Quoting Implementation is Secure and Robust

The genconn.SoftQuote implementation properly handles paths with spaces and special characters, including proper escaping and home directory expansion. The implementation is consistent across all shell integrations (bash, zsh, fish, and powershell).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that genconn.SoftQuote correctly quotes the bash RC path.

# Test: Search for occurrences of genconn.SoftQuote usage.
rg 'genconn\.SoftQuote\(' -A 2

Length of output: 1134


Script:

#!/bin/bash
# Find genconn.SoftQuote implementation
ast-grep --pattern 'func SoftQuote($$$) $$$'

# Check shellutil directory constants
rg 'BashIntegrationDir|WaveHomeBinDir|PwshIntegrationDir|ZshIntegrationDir' -A 1

Length of output: 5749

cmd/wsh/cmd/wshcmd-connserver.go (1)

193-193: Update Function Call After GetInfo Signature Change

The GetInfo function no longer accepts parameters. Ensure that the call to wshutil.GetInfo() reflects this change and that any dependent code is updated accordingly.

pkg/wshrpc/wshremote/wshremote.go (2)

21-21: Missing Import of wshutil Package

The wshutil package is now required due to the addition of RemoteGetInfoCommand. Ensure that the import statement is correctly added.


391-394: New RemoteGetInfoCommand Method Added

The RemoteGetInfoCommand method provides essential functionality for retrieving remote information. Ensure that this integration aligns with existing conventions and that any potential security implications are considered.

Please confirm that:

  • The method correctly retrieves and returns the necessary remote information.
  • Proper authentication and authorization checks are in place to prevent unauthorized access.

If you need assistance verifying the security aspects, I can help draft additional tests or suggest best practices.

pkg/wshutil/wshutil.go (1)

543-553: LGTM! Well-structured shell detection implementation.

The getShell() function provides a robust way to determine the user's shell with proper platform-specific handling for macOS and sensible fallbacks.

frontend/app/store/wshclientapi.ts (1)

245-249: LGTM! Clean and consistent RPC command implementation.

The RemoteGetInfoCommand implementation follows the established pattern and properly handles the RPC call.

pkg/wshrpc/wshclient/wshclient.go (1)

298-302: LGTM! Consistent with other RPC command implementations.

The RemoteGetInfoCommand implementation follows the established pattern and properly handles the RPC call and error cases.

pkg/wshrpc/wshrpctypes.go (2)

76-76: LGTM! Command constant follows naming convention.

The Command_RemoteGetInfo constant is properly defined and follows the established naming pattern.


183-183: LGTM! Interface method properly defined.

The RemoteGetInfoCommand method is correctly added to the interface with proper context handling.

pkg/remote/conncontroller/conncontroller.go (1)

382-382: LGTM! The logging change aligns with the PR objectives.

The change to use conn.GetName() instead of remoteInfo.ConnName is consistent with the PR's goal to update the remote shell identification mechanism.

Comment on lines +385 to +386
zshDir := genconn.SoftQuote(fmt.Sprintf("~/.waveterm/%s", shellutil.ZshIntegrationDir))
cmdCombined = fmt.Sprintf(`ZDOTDIR=%s %s`, zshDir, cmdCombined)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Environment Variable ZDOTDIR May Not Be Set Correctly

Setting ZDOTDIR after the session is created may not affect the Zsh initialization as expected. Consider setting ZDOTDIR before the session starts to ensure that the custom Zsh configuration is loaded.

Apply this diff to set ZDOTDIR before the session starts:

     for envKey, envVal := range cmdOpts.Env {
         // note these might fail depending on server settings, but we still try
         session.Setenv(envKey, envVal)
     }

+    if isZshShell(shellPath) {
+        zshDir := genconn.SoftQuote(fmt.Sprintf("~/.waveterm/%s", shellutil.ZshIntegrationDir))
+        session.Setenv("ZDOTDIR", zshDir)
+    }

     jwtToken, ok := cmdOpts.Env[wshutil.WaveJwtTokenVarName]
     if !ok {
         return nil, fmt.Errorf("no jwt token provided to connection")

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +193 to 196
remoteInfo := wshutil.GetInfo()
needsRestartRaw, err := RpcClient.SendRpcRequest(wshrpc.Command_ConnUpdateWsh, remoteInfo, &wshrpc.RpcOpts{Timeout: 60000})
if err != nil {
return fmt.Errorf("could not update: %w", err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle Potential Errors Gracefully

After modifying the GetInfo function call, ensure that any potential errors are handled appropriately, and provide informative error messages to aid in troubleshooting.

Consider checking for errors and updating the error handling logic if necessary.

Comment on lines +555 to 562
func GetInfo() wshrpc.RemoteInfo {
return wshrpc.RemoteInfo{
ConnName: rpcContext.Conn,
ClientArch: runtime.GOARCH,
ClientOs: runtime.GOOS,
ClientVersion: wavebase.WaveVersion,
Shell: os.Getenv("SHELL"),
Shell: getShell(),
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Shell path existence verification needed

The review comment is valid. The code assumes shell paths exist without verification:

  • For non-Darwin: uses $SHELL or falls back to "/bin/bash"
  • For Darwin: uses UserShell from dscl or falls back to "/bin/bash"
  • No existence check is performed at any point in the chain

Suggested locations to add verification:

  • pkg/wshutil/wshutil.go:getShell(): Verify returned path exists
  • pkg/util/shellutil/shellutil.go:GetMacUserShell(): Verify shell path before returning
🔗 Analysis chain

Verify shell path existence.

The shell path returned by getShell() should be verified to exist before being used in GetInfo().

Run this script to verify the shell paths:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the default shell paths exist
# Test: Check if common shell paths exist
echo "Checking default shell paths..."
for shell in "/bin/bash" "/bin/sh" "/bin/zsh"; do
  if [ -f "$shell" ]; then
    echo "Found: $shell"
  else
    echo "Missing: $shell"
  fi
done

# Test: Check if GetMacUserShell is properly implemented
echo "Checking for shellutil.GetMacUserShell implementation..."
rg -A 5 "func GetMacUserShell" 

Length of output: 911


Script:

#!/bin/bash
# Find getShell implementation and its dependencies
ast-grep --pattern 'func getShell()' -l go
rg -A 10 'func getShell\(\)' 

# Check for shell path validation
rg -i 'exists|stat|isfile|filepath' pkg/wshutil/

Length of output: 1817


Script:

#!/bin/bash
# Check GetMacUserShell implementation
rg -A 15 'func internalMacUserShell' pkg/util/shellutil/

Length of output: 1094


Script:

#!/bin/bash
# Check DefaultShellPath constant
rg "DefaultShellPath\s*=" pkg/util/shellutil/

Length of output: 116

@oneirocosm oneirocosm merged commit 0174e7c into main Jan 12, 2025
8 checks passed
@oneirocosm oneirocosm deleted the sylvie/info-rpc branch January 12, 2025 23:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant