Skip to content

Conversation

@johnlindquist
Copy link
Owner

@johnlindquist johnlindquist commented Jul 11, 2025

Summary

  • Added new session command to open latest session logs in the default editor
  • Improved payload type definitions with specific tool input/response types
  • Added hook_event_name property to all payload interfaces for better type discrimination

Changes

New Session Command

  • Added src/commands/session.ts implementing a new command to view session logs
  • Supports opening the latest session log by default
  • Includes --id flag to open a specific session by partial ID match
  • Includes --list flag to display all available sessions with timestamps
  • Automatically opens logs in the system's default editor

Improved Type Definitions

  • Updated templates/hooks/lib.ts with better payload type definitions
  • Added hook_event_name property to all payload interfaces (PreToolUse, PostToolUse, Notification, Stop, SubagentStop)
  • This enables better type discrimination when handling different hook events
  • Maintains backward compatibility while providing clearer type information

Test plan

  • All existing tests pass
  • Linting passes
  • Test the new session command functionality
  • Verify type improvements don't break existing hook implementations

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a command to manage and open session log files, including listing all sessions and opening specific logs by session ID.
  • Improvements
    • Enhanced hook payloads with a new event name property for clearer identification.
  • Breaking Changes
    • Removed the title property from notification payloads, which may affect integrations relying on this field.

johnlindquist and others added 2 commits July 11, 2025 11:01
- Add new `session` command to open latest session logs in default editor
- Improve payload type definitions with specific tool input/response types
- Add hook_event_name property to all payload interfaces for better type discrimination
- Support opening session logs by ID or latest session
- Add proper error handling and user feedback

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@johnlindquist johnlindquist enabled auto-merge July 11, 2025 17:03
@coderabbitai
Copy link

coderabbitai bot commented Jul 11, 2025

Walkthrough

A new CLI command for managing Claude session log files was introduced, allowing users to list and open session logs via platform-specific editors. Additionally, all exported hook payload interfaces were updated to include a fixed event name property, and the title property was removed from the notification payload interface.

Changes

File(s) Change Summary
src/commands/session.ts Added a new CLI command class Session to list and open session log files with platform support.
templates/hooks/lib.ts Added hook_event_name string literal property to all hook payload interfaces; removed title from NotificationPayload.

Poem

In the warren, logs now gleam and shine,
With sessions listed, sorted fine.
Hooks announce their names with pride,
No more titles left to hide.
Rabbits hop and softly cheer—
New commands and types are here!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@johnlindquist johnlindquist merged commit 8e068f7 into main Jul 11, 2025
9 of 10 checks passed
Copy link

@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: 1

🧹 Nitpick comments (1)
src/commands/session.ts (1)

94-99: Improve ID matching with better user feedback.

The current ID matching implementation could provide better user feedback when multiple sessions match the partial ID.

Consider improving the ID matching logic:

   if (flags.id) {
-    targetFile = fileStats.find((stat) => stat.sessionId.toLowerCase().includes(flags.id!.toLowerCase()))
+    const matches = fileStats.filter((stat) => stat.sessionId.toLowerCase().includes(flags.id!.toLowerCase()))
+    if (matches.length === 0) {
-      if (!targetFile) {
         console.log(chalk.red(`No session found matching ID: ${flags.id}`))
         return
-      }
+    } else if (matches.length > 1) {
+      console.log(chalk.yellow(`Multiple sessions found matching "${flags.id}". Using the most recent:`))
+      matches.slice(0, 3).forEach((match, index) => {
+        const marker = index === 0 ? chalk.green('→') : ' '
+        console.log(`${marker} ${chalk.cyan(match.sessionId)} ${chalk.gray(match.mtime.toLocaleString())}`)
+      })
+      if (matches.length > 3) {
+        console.log(chalk.gray(`... and ${matches.length - 3} more`))
+      }
+    }
+    targetFile = matches[0]
   } else {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f99cbef and 2f218ad.

📒 Files selected for processing (2)
  • src/commands/session.ts (1 hunks)
  • templates/hooks/lib.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
templates/**/*

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
src/commands/**/*

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to **/*.integration.{ts,js} : Integration tests should test the full CLI behavior.
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to .claude/{settings.json,hooks/index.ts,hooks/lib.ts,hooks/session.ts} : The CLI generates a '.claude/' directory containing 'settings.json', 'hooks/index.ts', 'hooks/lib.ts', and 'hooks/session.ts' when initialized.
src/commands/session.ts (1)
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to .claude/{settings.json,hooks/index.ts,hooks/lib.ts,hooks/session.ts} : The CLI generates a '.claude/' directory containing 'settings.json', 'hooks/index.ts', 'hooks/lib.ts', and 'hooks/session.ts' when initialized.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: test (windows-latest, 18)
  • GitHub Check: test (windows-latest, 20)
🔇 Additional comments (3)
templates/hooks/lib.ts (1)

10-10: LGTM! Excellent type discrimination enhancement.

The addition of hook_event_name with string literal types to all payload interfaces is a well-designed improvement that enables proper type discrimination at runtime. The consistent naming pattern across all interfaces enhances maintainability.

Also applies to: 18-18, 29-29, 36-36, 43-43

src/commands/session.ts (2)

8-37: Well-structured command implementation.

The command class is well-organized with clear documentation, appropriate flags, and helpful examples. The static properties follow oclif conventions properly.


42-44: Critical Issue: Session directory mismatch.

The session command is looking for session files in the system temp directory (claude-hooks-sessions), but the session management utilities in templates/hooks/lib.ts save sessions to .claude/hooks/sessions relative to the current working directory. This mismatch will cause the command to never find any session files.

Apply this fix to use the correct sessions directory:

-    // Get the sessions directory from temp
-    const tempDir = os.tmpdir()
-    const sessionsDir = path.join(tempDir, 'claude-hooks-sessions')
+    // Get the sessions directory from .claude/hooks/sessions
+    const sessionsDir = path.join(process.cwd(), '.claude', 'hooks', 'sessions')
⛔ Skipped due to learnings
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to .claude/{settings.json,hooks/index.ts,hooks/lib.ts,hooks/session.ts} : The CLI generates a '.claude/' directory containing 'settings.json', 'hooks/index.ts', 'hooks/lib.ts', and 'hooks/session.ts' when initialized.
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to **/*.integration.{ts,js} : Integration tests should test the full CLI behavior.
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to src/commands/**/* : Commands must be implemented in the 'src/commands/' directory; currently, only the main 'init' command exists there.
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Session logs are written to the system temp directory.
Learnt from: CR
PR: johnlindquist/claude-hooks#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-07T16:54:50.723Z
Learning: Applies to templates/**/* : Hook templates must be stored in the 'templates/' directory and are copied to the user's '.claude/' directory during initialization.

Comment on lines +132 to +147
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: 'ignore',
detached: true,
})

child.on('error', (error) => {
console.error(chalk.red('Failed to open file:'), error.message)
console.log(chalk.gray('You can manually open the file at:'))
console.log(chalk.cyan(filePath))
reject(error)
})

child.unref()
resolve()
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and process management.

The file opening logic has a few issues:

  1. The Promise resolves immediately without waiting for the process to actually start
  2. Error handling could provide better user feedback
  3. The process management could be more robust

Apply this improvement:

-    return new Promise((resolve, reject) => {
+    return new Promise((resolve, reject) => {
       const child = spawn(command, args, {
         stdio: 'ignore',
         detached: true,
       })
 
+      child.on('spawn', () => {
+        child.unref()
+        resolve()
+      })
+
       child.on('error', (error) => {
         console.error(chalk.red('Failed to open file:'), error.message)
         console.log(chalk.gray('You can manually open the file at:'))
         console.log(chalk.cyan(filePath))
         reject(error)
       })
-
-      child.unref()
-      resolve()
     })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: 'ignore',
detached: true,
})
child.on('error', (error) => {
console.error(chalk.red('Failed to open file:'), error.message)
console.log(chalk.gray('You can manually open the file at:'))
console.log(chalk.cyan(filePath))
reject(error)
})
child.unref()
resolve()
})
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: 'ignore',
detached: true,
})
child.on('spawn', () => {
child.unref()
resolve()
})
child.on('error', (error) => {
console.error(chalk.red('Failed to open file:'), error.message)
console.log(chalk.gray('You can manually open the file at:'))
console.log(chalk.cyan(filePath))
reject(error)
})
})
🤖 Prompt for AI Agents
In src/commands/session.ts lines 132 to 147, the Promise resolves immediately
after spawning the child process without confirming it started successfully, and
error handling lacks detailed user feedback. Modify the code to resolve the
Promise only after the child process has successfully started, enhance error
handling to provide clearer user messages including the file path, and improve
process management by ensuring the child process is properly detached and
unreferenced. This will make the file opening logic more reliable and
user-friendly.

@github-actions
Copy link
Contributor

🎉 This PR is included in version 1.4.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants