Skip to content

Conversation

@mibeco
Copy link
Owner

@mibeco mibeco commented Sep 27, 2025

Problem

The AWS documentation states that users can reset their default agent by running:

q settings chat.defaultAgent ""

However, this currently causes an error message on every chat session start:

Error: user defined default  not found. Falling back to in-memory default

Root Cause

The issue occurs because:

  1. Setting an empty string "" stores it as a valid string value in the database
  2. get_string() returns Some("") for empty strings, not None
  3. The agent selection logic tries to find an agent named "" (empty string)
  4. When it fails to find this agent, it shows the error message

Solution

This PR modifies the agent selection logic to treat empty strings as "no default set", allowing users to cleanly reset to the built-in default agent without error messages.

Changes

  • Modified crates/chat-cli/src/cli/agent/mod.rs to check !user_set_default.is_empty() before attempting to find the agent
  • Empty strings now silently fall through to the built-in default agent
  • Non-empty invalid agent names still show appropriate error messages

Testing

The fix ensures that:

  • q settings chat.defaultAgent "" works as documented (no error messages)
  • q settings chat.defaultAgent "invalid-agent" still shows error messages
  • Normal agent selection continues to work as expected

Fixes the misleading behavior described in the AWS documentation where setting an empty string should reset to built-in default silently.

xianwwu and others added 30 commits September 2, 2025 09:27
…generate (aws#2741)

* fixing bugs

* formatting

* fix: CTRL+C handling during multi-select, auto completion for /agent generate

* set use legacy mcp config to false

---------

Co-authored-by: Xian Wu <xianwwu@amazon.com>
- Changed from ~/.q/knowledge_bases/ to ~/.aws/amazonq/knowledge_bases/
- Default agent uses q_cli_default/ (no alphanumeric suffix)
- Custom agents use <agent-name>_<alphanumeric-code>/ format

Co-authored-by: Kenneth S. <kennvene@amazon.com>
- Add Drop trait to InputSource for automatic history saving
- Replace DefaultHistory with FileHistory for persistence
- Store history in ~/.aws/amazonq/cli_history
- Refactor ChatHinter to use rustyline's built-in history search
- Remove manual history tracking in favor of rustyline's implementation
- Add history loading on startup with error handling
- Clean up unused hinter history update methods
* comment profile set

* comment profile in apiclient

* add a helper func

* fix compile issue

* remove dead code tag
* client struct definition

* clean up unused code

* adds mechanism for checking if server is alive

* prefetches prompts if applicable

* fixes agent swap

fixes agent swap

* only applies process group leader promo for unix

* removes unused import for windows

* renames abstractions for different stages of mcp config
- Add file://AGENTS.md to default resources list alongside AmazonQ.md
- Update test to include both AmazonQ.md and AGENTS.md files
- Ensures AGENTS.md is included everywhere AmazonQ.md was previously included

Co-authored-by: Matt Lee <mr-lee@users.noreply.github.com>
- Add optional 'model' field to Agent struct for specifying model per agent
- Update JSON schema and documentation with model field usage
- Integrate agent model into model selection priority:
  1. CLI argument (--model)
  2. Agent's model field (new)
  3. User's saved default model
  4. System default model
- Add proper fallback when agent specifies unavailable model
- Extract fallback logic to eliminate code duplication
- Include comprehensive unit tests for model field functionality
- Maintain backward compatibility with existing agent configurations

Co-authored-by: Matt Lee <mr-lee@users.noreply.github.com>
* Properly handle path with trailing slash in file matching

Today if a path has a trailing slash, the glob pattern will look like
"/path-to-folder//**" (note the double slash). Glob doesn't work with
double slash actually (it doesn't match anything). As a result, the
permission management for fs_read and fs_write is broken when allowed
or denied path has trailing slash.

The fix is to just manually remove the trailing slash.

* format change
* add a wrapmode in chat args

* add a ut for the wrap arg
- Add auto_allow_readonly field to use_aws Settings struct (defaults to false)
- Update eval_perm method to use auto_allow_readonly setting instead of hardcoded behavior
- Default behavior: all AWS operations require user confirmation (secure by default)
- Opt-in behavior: when autoAllowReadonly=true, read-only operations are auto-approved
- Add comprehensive tests covering all scenarios
- Maintains backward compatibility through configuration

🤖 Assisted by Amazon Q Developer

Co-authored-by: Matt Lee <mr-lee@users.noreply.github.com>
…s#2838)

Users can now keep the final question and answer from tangent mode
by using `/tangent tail` instead of `/tangent`. This preserves the last
Q&A pair when returning to the main conversation, making it easy to
retain helpful insights discovered during exploration.

- `/tangent` - exits tangent mode (existing behavior unchanged)
- `/tangent tail` - exits tangent mode but keeps the last Q&A pair

This enables users to safely explore topics without losing the final
valuable insight that could benefit their main conversation flow.
Tracks daily active users by sending amazonqcli_dailyHeartbeat
event once per day. Uses fail-closed logic to prevent spam
during database errors.
* docs: fix local agent directory path

- Fix local agent path from .aws/amazonq/cli-agents/ to .amazonq/cli-agents/
- Global paths (~/.aws/amazonq/cli-agents/) remain correct
- Aligns documentation with source code implementation

* fix: correct workspace agent path in /agent help message

The help message for the /agent command incorrectly showed the workspace
agent path as 'cwd/.aws/amazonq/cli-agents' when it should be
'cwd/.amazonq/cli-agents' (without the .aws directory).

This fix aligns the help text with the actual WORKSPACE_AGENT_DIR_RELATIVE
constant defined in directories.rs.
…urity (aws#2846)

- Change default_allow_read_only() from true to false for secure by default behavior
- Default behavior: all bash commands require user confirmation (secure by default)
- Opt-in behavior: when autoAllowReadonly=true, read-only commands are auto-approved
- Use autoAllowReadonly casing to match use_aws tool pattern
- Update documentation to reflect new default value and consistent naming
- Add comprehensive tests covering all scenarios
- Maintains backward compatibility through configuration
- Follows same pattern as use_aws autoAllowReadonly setting

🤖 Assisted by Amazon Q Developer

Co-authored-by: Matt Lee <mrlee@amazon.com>
- Add Edit subcommand to AgentSubcommands enum
- Implement edit functionality that opens existing agent files in editor
- Use Agent::get_agent_by_name to locate and load existing agents
- Include post-edit validation to ensure JSON remains valid
- Add comprehensive tests for the new edit subcommand
- Support both --name and -n flags for agent name specification

🤖 Assisted by Amazon Q Developer

Co-authored-by: Matt Lee <mr-lee@users.noreply.github.com>
dingfeli and others added 27 commits September 17, 2025 10:52
* Change autocomplete shortcut from ctrl-f to ctrl-g

The reason is ctrl-f is the standard shortcut in UNIX for moving cursor
forward by 1 character. You can find it being supported everywhere...
in your browser, your terminal, etc.

* make the autocompletion key configurable
* fix incorrect scope for mcp oauth

* reverts custom tool config enum change

* fixes display task overriding sign in notice

* updates schema
)

Reset tool_uses, pending_tool_index, and tool_turn_start_time to prevent
orphaned tool approval prompts after conversation history is cleared.

Co-authored-by: Niraj Chowdhary <chownira@amazon.com>
aws#2975)

* fix: consolidate tool permission logic for consistent display and execution

* fix: centralize tool permission checking logic

---------

Co-authored-by: Niraj Chowdhary <chownira@amazon.com>
* feat: expand support for /prompts command

* fix: prompts spec

* fix: add /prompts delete cmd

* fix(prompts): improve validation and user input handling

* fix(prompts): manage prompt using structs
Co-authored-by: Kenneth S. <kennvene@amazon.com>
Add experimental feature to show context window usage as a percentage
in the chat prompt (e.g., "[rust-agent] 6% >"). The percentage is
color-coded: green (<50%), yellow (50-89%), red (90-100%).

The feature is disabled by default and can be enabled via /experiment.
* [fix] Fixes issues with Tool Input parsing.
* Ocassionally the model will generate a tool use which parameters are not a valid json. When this happens it corrupts the conversation history.
* Here we first avoid storing the tool use and add the propert validation logic to the conversation history.

* adds validation logic to safety

* [fix] Update to use a new RecvErrorKind instead of custom error handling.

* [fix] Gives visual hint to the user, that request is being retried.

---------

Co-authored-by: Kenneth S. <kennvene@amazon.com>
* (in progress) Implement checkpointing using git CLI commands

* feat: Add new checkpointing functionality using git CLI

Updates:
- Only works if the user has git installed
- Supports auto initialization if the user is in a git repo, manual
if not
- UI ported over from dedicated file tools implementation

* feat: Add user message for turn-level checkpoints, clean command

Updates:
- The clean subcommand will delete the shadow repo
- The description for turn-level checkpoints is a truncated version
of the user's last message

* fix: Fix shadow repo deletion logic

Updates:
- Running the clean subcommand now properly deletes the entire
shadow repo for both automatic and manual modes

* chore: Run formatter and fix clippy warnings

* feat: Add checkpoint diff

Updates:
- Users can now view diffs between checkpoints
- Fixed tool-level checkpoint display handling

* fix: Fix last messsage handling for checkpoints

Updates:
- Checkpoints now (hopefully) correctly display the correct
turn-specific user message
- Added slash command auto completion

* fix: Fix commit message handling again

* chore: Run formatter

* Removed old comment

* define a global capture dirctory

* revise the capture path

* fix cpature clean bug

* add a clean all flag

* add auto drop method for capture feature

* support file details when expand

* add the file summary when list and expand

* revise structure and print no diff msg

* delete all flag, add summry when fs read

* refactor code

* revise ui

* add capture into experiement

* clippy

* rename to checkpoint

* reverse false renaming

* recover history

* disable tangent mode in checkpoint

* fix cr

* nit: keep checkpoint name

* allow both tangent & checkpoint enabled

* ci

---------

Co-authored-by: kiran-garre <kiranbug@amazon.com>
Co-authored-by: Kenneth S. <kennvene@amazon.com>
Add version note indicating that agent-specific knowledge bases are
available in development but not in current releases (v1.14.1 and earlier).
Current releases use global storage at ~/.aws/amazonq/knowledge_bases/.
When users run 'q settings chat.defaultAgent ""' to reset their default
agent (as documented), the empty string was being treated as a valid
agent name, causing an error message on every chat session start.

This change treats empty strings as 'no default set', allowing users
to cleanly reset to the built-in default agent without error messages.

Fixes the misleading behavior described in the AWS documentation where
setting an empty string should reset to built-in default silently.
@amazon-q-developer
Copy link

Code review in progress. Analyzing for code quality issues and best practices. Detailed findings will be posted upon completion.

Using Amazon Q Developer for GitHub

Amazon Q Developer1 is an AI-powered assistant that integrates directly into your GitHub workflow, enhancing your development process with intelligent features for code development, review, and transformation.

Slash Commands

Command Description
/q <message> Chat with the agent to ask questions or request revisions
/q review Requests an Amazon Q powered code review
/q help Displays usage information

Features

Agentic Chat
Enables interactive conversation with Amazon Q to ask questions about the pull request or request specific revisions. Use /q <message> in comment threads or the review body to engage with the agent directly.

Code Review
Analyzes pull requests for code quality, potential issues, and security concerns. Provides feedback and suggested fixes. Automatically triggered on new or reopened PRs (can be disabled for AWS registered installations), or manually with /q review slash command in a comment.

Customization

You can create project-specific rules for Amazon Q Developer to follow:

  1. Create a .amazonq/rules folder in your project root.
  2. Add Markdown files in this folder to define rules (e.g., cdk-rules.md).
  3. Write detailed prompts in these files, such as coding standards or best practices.
  4. Amazon Q Developer will automatically use these rules when generating code or providing assistance.

Example rule:

All Amazon S3 buckets must have encryption enabled, enforce SSL, and block public access.
All Amazon DynamoDB Streams tables must have encryption enabled.
All Amazon SNS topics must have encryption enabled and enforce SSL.
All Amazon SNS queues must enforce SSL.

Feedback

To provide feedback on Amazon Q Developer, create an issue in the Amazon Q Developer public repository.

For more detailed information, visit the Amazon Q for GitHub documentation.

Footnotes

  1. Amazon Q Developer uses generative AI. You may need to verify generated code before using it in your environment. See the AWS Responsible AI Policy.

Copy link

@amazon-q-developer amazon-q-developer bot left a comment

Choose a reason for hiding this comment

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

Summary

This PR successfully addresses the core issue described in the title - fixing empty string handling for the chat.defaultAgent setting. The main fix in crates/chat-cli/src/cli/agent/mod.rs correctly treats empty strings as "no default set" rather than attempting to find an agent with an empty name.

Key Findings

Positive Changes

  • Core Fix: The empty string check (!user_set_default.is_empty()) properly resolves the documented behavior issue
  • Security Improvements: Custom endpoint detection prevents credential leakage to non-AWS endpoints
  • Error Handling: Better SDK error formatting with SdkErrorDisplay wrapper

⚠️ Security Concerns

  • Command Injection Risks: Both download_feed_json() in build.rs and run_git() in checkpoint.rs execute external commands with insufficient input validation
  • Network Security: The build script downloads content from GitHub without integrity verification

📋 Recommendations

  1. High Priority: Address command injection vulnerabilities in build.rs and checkpoint.rs
  2. Medium Priority: Consider more conservative version bumping (patch vs minor for bug fixes)
  3. Low Priority: Add test coverage for the empty string handling behavior

Scope Concern

While the PR title suggests a focused bug fix, this PR includes substantial new functionality (93 files changed, 8695 additions). Consider splitting large feature additions from critical bug fixes in future PRs for easier review and safer deployment.

The core fix is solid and addresses the documented issue effectively. The security vulnerabilities should be addressed before merging.

if all_agents.iter().any(|a| a.name == user_set_default) {
break 'active_idx user_set_default;
// Treat empty strings as "no default set" to allow clean reset
if !user_set_default.is_empty() {

Choose a reason for hiding this comment

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

Excellent Fix: This change correctly addresses the issue described in the PR. The addition of !user_set_default.is_empty() check ensures that empty strings are treated as "no default set" rather than attempting to find an agent with an empty name.

This allows users to cleanly reset their default agent using q settings chat.defaultAgent "" as documented, without triggering the error message. The logic properly falls through to the built-in default agent when an empty string is provided, which is the expected behavior.

if all_agents.iter().any(|a| a.name == user_set_default) {
break 'active_idx user_set_default;
// Treat empty strings as "no default set" to allow clean reset
if !user_set_default.is_empty() {

Choose a reason for hiding this comment

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

Suggestion: Consider adding a test case to verify the empty string handling behavior. This would help ensure the fix continues to work correctly and documents the expected behavior.

homepage = "https://aws.amazon.com/q/"
publish = false
version = "1.15.0"
version = "1.16.3"

Choose a reason for hiding this comment

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

The version bump from 1.15.0 to 1.16.3 seems significant for what appears to be a bug fix. Consider using semantic versioning more strictly - this type of bug fix would typically warrant a patch version increment (e.g., 1.15.1) rather than a minor version jump to 1.16.3.

Comment on lines +330 to +386

/// Downloads the latest feed.json from the autocomplete repository.
/// This ensures official builds have the most up-to-date changelog information.
///
/// # Errors
///
/// Prints cargo warnings if:
/// - `curl` command is not available
/// - Network request fails
/// - File write operation fails
fn download_feed_json() {
use std::process::Command;

println!("cargo:warning=Downloading latest feed.json from autocomplete repo...");

// Check if curl is available first
let curl_check = Command::new("curl").arg("--version").output();

if curl_check.is_err() {
panic!(
"curl command not found. Cannot download latest feed.json. Please install curl or build without FETCH_FEED=1 to use existing feed.json."
);
}

let output = Command::new("curl")
.args([
"-H",
"Accept: application/vnd.github.v3.raw",
"-f", // fail on HTTP errors
"-s", // silent
"-v", // verbose output printed to stderr
"--show-error", // print error message to stderr (since -s is used)
"https://api.github.com/repos/aws/amazon-q-developer-cli-autocomplete/contents/feed.json",
])
.output();

match output {
Ok(result) if result.status.success() => {
if let Err(e) = std::fs::write("src/cli/feed.json", result.stdout) {
panic!("Failed to write feed.json: {}", e);
} else {
println!("cargo:warning=Successfully downloaded latest feed.json");
}
},
Ok(result) => {
let error_msg = if !result.stderr.is_empty() {
format!("{}", String::from_utf8_lossy(&result.stderr))
} else {
"An unknown error occurred".to_string()
};
panic!("Failed to download feed.json: {}", error_msg);
},
Err(e) => {
panic!("Failed to execute curl: {}", e);
},
}
}

Choose a reason for hiding this comment

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

🛑 Security Vulnerability: The download_feed_json() function has several security concerns:

  1. Command Injection Risk: The function executes curl with arguments that could potentially be manipulated if the URL or other parameters were user-controlled.

  2. Network Security: Downloads content from GitHub API without certificate validation or integrity checks.

  3. File System Risk: Overwrites src/cli/feed.json without proper validation of the downloaded content.

Recommendations:

  • Validate the downloaded JSON content before writing to disk
  • Add checksum verification for the downloaded file
  • Consider using a Rust HTTP client instead of shelling out to curl
  • Add timeout and size limits for the download

println!("cargo:warning=Downloading latest feed.json from autocomplete repo...");

// Check if curl is available first
let curl_check = Command::new("curl").arg("--version").output();

Choose a reason for hiding this comment

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

Code Quality Issue: Using panic! in build scripts can cause confusing build failures. Consider using cargo:warning= directives to emit warnings instead of panicking, or provide more graceful fallback behavior when curl is not available or network requests fail.

This would make the build more resilient in environments where network access is restricted or curl is not installed.

Comment on lines +375 to +378
}

// Tag
let output = run_git(Path::new(shadow_path), false, &["tag", tag])?;

Choose a reason for hiding this comment

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

🛑 Command Injection Vulnerability: The run_git function constructs git commands with user-controlled input without proper sanitization. The args parameter could potentially contain malicious command arguments.

Recommendation: Validate and sanitize all arguments passed to git commands, or use a git library instead of shelling out to the git binary.

Suggested change
}
// Tag
let output = run_git(Path::new(shadow_path), false, &["tag", tag])?;
fn run_git(dir: &Path, with_work_tree: bool, args: &[&str]) -> Result<Output> {
// Validate git arguments to prevent command injection
for arg in args {
if arg.contains(';') || arg.contains('|') || arg.contains('&') {
bail!("Invalid git argument: {}", arg);
}
}
let mut cmd = Command::new("git");
cmd.arg(format!("--git-dir={}", dir.display()));
if with_work_tree {
cmd.arg("--work-tree=.");
}
cmd.args(args);
let output = cmd.output()?;
if !output.status.success() && !output.stderr.is_empty() {
bail!(String::from_utf8_lossy(&output.stderr).to_string());
}
Ok(output)
}

Comment on lines +23 to +25
#[error("{}", SdkErrorDisplay(.0))]
SdkRegisterClient(Box<SdkError<RegisterClientError>>),
#[error(transparent)]
#[error("{}", SdkErrorDisplay(.0))]

Choose a reason for hiding this comment

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

Good Practice: The addition of SdkErrorDisplay wrapper for better error formatting is a good improvement. This provides more user-friendly error messages while maintaining the underlying error information for debugging.

}

// Add a helper method to check if using non-default endpoint
fn is_custom_endpoint(database: &Database) -> bool {

Choose a reason for hiding this comment

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

Good Security Practice: The addition of custom endpoint detection (is_custom_endpoint) and conditional profile handling is a good security improvement. This prevents attempting to use AWS profiles when connecting to non-AWS endpoints, which could potentially leak credentials or cause authentication errors.

@mibeco mibeco closed this Sep 27, 2025
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.