Skip to content

Conversation

@BYK
Copy link
Member

@BYK BYK commented Jan 30, 2026

Summary

Improves Sentry telemetry for better observability and debugging of CLI usage.

Changes

  • Better tracing: Add spans for HTTP requests, database operations, and serialization
  • User context: Track authenticated user ID and CLI instance ID (no PII)
  • Command context: Tag spans with command name, org/project when available
  • Auth feedback: Show username after successful login
  • Faster exit: Patch @sentry/core to prevent 3s flush timeout from blocking CLI exit

Technical Notes

  • Uses @sentry/bun for native builds, aliased to @sentry/node for npm bundle
  • Adds user_info and instance_info tables (schema v2 migration)
  • UUIDv7 for instance IDs via Bun.randomUUIDv7() (polyfilled for Node.js)

- Switch from @sentry/node to @sentry/bun with esbuild alias for npm bundle
- Add descriptive command names to spans (e.g., 'auth.login' instead of 'cli-execution')
- Add HTTP instrumentation for API client and OAuth calls
- Add DB instrumentation for auth/config operations
- Add serialize instrumentation for expensive formatters
- Track user identity (ID only, no PII) and instance ID for telemetry
- Add org/project context tags in issue commands
- Add schema migration v1→v2 for user_info and instance_info tables
- Fix race condition in instance ID generation with INSERT OR IGNORE
@github-actions
Copy link

github-actions bot commented Jan 30, 2026

Semver Impact of This PR

🟡 Minor (new features)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


New Features ✨

  • (api) Add custom User-Agent header to API requests by BYK in #125
  • (docs) Add Sentry SDK for error tracking, replay, and metrics by betegon in #122
  • (project) Improve project list and view output by betegon in #129
  • (telemetry) Improve Sentry instrumentation by BYK in #127

Bug Fixes 🐛

  • (npx) Suppress Node.js warnings in npm package by BYK in #115

Internal Changes 🔧

  • Allow PRs to merge when CI jobs are skipped by BYK in #123

🤖 This preview updates automatically when you update the PR.

…nstrumentation

# Conflicts:
#	src/lib/telemetry.ts
@github-actions
Copy link

github-actions bot commented Jan 30, 2026

Codecov Results 📊

❌ Patch coverage is 68.98%. Project has 1760 uncovered lines.
✅ Project coverage is 67.66%. Comparing base (base) to head (head).

Files with missing lines (24)
File Patch % Lines
human.ts 30.90% ⚠️ 682 Missing
resolve-target.ts 18.93% ⚠️ 257 Missing
oauth.ts 25.39% ⚠️ 191 Missing
resolver.ts 3.23% ⚠️ 120 Missing
api-client.ts 67.61% ⚠️ 103 Missing
errors.ts 5.94% ⚠️ 95 Missing
migration.ts 47.44% ⚠️ 82 Missing
api.ts 89.80% ⚠️ 47 Missing
seer.ts 75.54% ⚠️ 45 Missing
errors.ts 73.17% ⚠️ 33 Missing
seer.ts 76.15% ⚠️ 31 Missing
preload.ts 39.02% ⚠️ 25 Missing
detector.ts 87.79% ⚠️ 16 Missing
auth.ts 94.21% ⚠️ 7 Missing
index.ts 95.06% ⚠️ 4 Missing
colors.ts 91.84% ⚠️ 4 Missing
telemetry.ts 97.28% ⚠️ 4 Missing
schema.ts 88.00% ⚠️ 3 Missing
env-file.ts 97.17% ⚠️ 3 Missing
utils.ts 98.64% ⚠️ 2 Missing
alias.ts 98.56% ⚠️ 2 Missing
project-aliases.ts 97.40% ⚠️ 2 Missing
java.ts 97.22% ⚠️ 1 Missing
parser.ts 98.63% ⚠️ 1 Missing
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
+ Coverage    66.66%    67.66%       +1%
==========================================
  Files           45        47        +2
  Lines         5297      5442      +145
  Branches         0         0         —
==========================================
+ Hits          3531      3682      +151
- Misses        1766      1760        -6
- Partials         0         0         —

Generated by Codecov Action

@BYK BYK requested a review from betegon January 30, 2026 14:36
ky already handles retries via apiRequest/createApiClient with
exponential backoff. Manual retry loop was redundant.
@BYK
Copy link
Member Author

BYK commented Jan 30, 2026

Addressed in e2da7c4 - removed the manual retry loop since getCurrentUser()apiRequest()createApiClient() already configures ky with retry logic (2 retries, exponential backoff up to 10s, retries on 408/429/5xx).

- Report errors to Sentry in catch block (login.ts)
- Use getCurrentUser() for token validation, combining validation + user fetch
- Fold clearUserInfo() into clearAuth() for single logout operation
- Change setOrgProjectContext to accept arrays for org/project tags
- Use uuidv7 npm package in node-polyfills.ts (Bun has native support)
- Abstract schema table definitions to single source of truth
@BYK BYK force-pushed the feat/improve-sentry-instrumentation branch 2 times, most recently from 3c3262f to 637f1fe Compare January 30, 2026 18:51
@BYK BYK force-pushed the feat/improve-sentry-instrumentation branch from 637f1fe to deae9db Compare January 30, 2026 18:53
BYK added 4 commits January 30, 2026 19:02
…or v10.38.0

- Add user.json fixture and /api/0/users/me/ mock route for auth E2E tests
- Create patch for @sentry/[email protected] (used by @sentry/[email protected])
- Keep existing patch for @sentry/[email protected] (used by @sentry/[email protected])
- Upgrade @sentry/node from 10.36.0 to 10.38.0
- Remove @sentry/[email protected] patch (no longer needed)
- Keep single @sentry/[email protected] patch for both @sentry/bun and @sentry/node
Display 'Logged in as username <email>' after successful authentication
for both token-based and OAuth flows.
- Add Sentry.captureException in telemetry.ts initTelemetryContext catch block
- Abstract connection error handling into fetchWithConnectionError() in oauth.ts
- Remove redundant divider comments in schema.ts and oauth.ts
@BYK
Copy link
Member Author

BYK commented Jan 30, 2026

Addressing PR Review Comments

I've made the following code changes in commit 912781f:

  1. Add Sentry.captureException in telemetry.ts - Added error capture in the initTelemetryContext() catch block
  2. Abstract connection error handling - Created fetchWithConnectionError() helper in oauth.ts to DRY up the repeated pattern
  3. Remove redundant divider comments - Cleaned up // ───... comment blocks in schema.ts and oauth.ts

Responses to Questions:

Q: Will withHttpSpan wrapper interfere with existing fetch instrumentation?

No, they complement each other:

  • httpIntegration() auto-instruments all fetch calls globally
  • withHttpSpan adds explicit spans for OAuth calls that need custom error handling and aren't using ky
  • The spans will nest properly - the http integration creates the outer span, withHttpSpan creates a more specifically-named inner span

Q: Why not using ky in oauth.ts?

OAuth uses native fetch because:

  • Device flow has specific polling requirements (interval, slow_down handling)
  • Different error response schemas (TokenErrorResponse vs standard API errors)
  • Needs fine-grained control over retry behavior (polling intervals from server)
  • The error handling is more complex than standard API calls (multiple response schemas to parse)

Q: Does SQLite have a built-in uuidv7 function?

No, SQLite doesn't have built-in UUIDv7 support. Standard SQLite only provides:

  • randomblob(16) for random bytes
  • hex() for hex encoding

UUIDv7 requires specific timestamp encoding in the first 48 bits that SQLite doesn't provide natively. Using Bun.randomUUIDv7() (with uuidv7 npm polyfill for Node.js) is the correct approach.


Already Addressed in Previous Commits:

  • ✅ Use ky for login.ts retries → Retry logic removed; uses getCurrentUser() which uses ky
  • ✅ Report errors to Sentry in catch block → Added Sentry.captureException(error) in OAuth flow
  • ✅ Use fetchAndStoreUserInfo for validation → Refactored to use getCurrentUser() directly
  • ✅ Fold clearUserInfo into clearAuth → clearAuth() now deletes from user_info table
  • ✅ Make org/project arrays → setOrgProjectContext() accepts string arrays
  • ✅ Use npm package for UUIDv7 → Uses Bun.randomUUIDv7() with uuidv7 polyfill
  • ✅ Schema repetition → Table definitions extracted to constants, used in both init and migrations

@BYK BYK marked this pull request as ready for review January 30, 2026 20:09
- Add tests for setCommandSpanName, setOrgProjectContext
- Add tests for withHttpSpan, withDbSpan, withSerializeSpan
- Add comprehensive tests for user.ts (getUserInfo, setUserInfo, clearUserInfo)
- CI: Ensure retry loop fails when all attempts exhausted (exit 1)
- telemetry: Use dynamic import() instead of require() for ES module compatibility
- user.ts: Remove unused clearUserInfo export (now handled by clearAuth)
Add formatUserIdentity() helper to gracefully handle cases where
username and/or email are undefined in the Sentry API response.

Fallback order:
1. username <email> (both present)
2. username (only username)
3. email (only email)
4. user {id} (neither present)
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.

Database errors in setUserInfo() were incorrectly being treated as
invalid token errors. Now the flows are:
1. getCurrentUser() validates token - failure clears auth
2. setUserInfo() stores telemetry data - failure is reported to Sentry

This matches the OAuth flow pattern and prevents valid tokens from
being cleared due to unrelated database errors.
@BYK BYK merged commit 037d18f into main Jan 30, 2026
24 checks passed
@BYK BYK deleted the feat/improve-sentry-instrumentation branch January 30, 2026 21:01
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.

3 participants