Phase 2: Testing seams (database, CLI handlers, connections) - #36
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reached
Next review available in: 45 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (9)
📝 WalkthroughWalkthroughThe PR extracts CLI turn orchestration into a testable utility, adds CLI and connections unit tests, adds isolated database repository integration tests, exposes host normalization, and configures integration-test scripts, CI execution, and testing-environment documentation. ChangesCLI testing seams
Connections coverage
Database integration
CI and documentation
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Introduce Turso repository integration tests, extract controller runTurn, add stream and ACP mapper coverage, test signaling helpers, and add a postgres-js factory for future server integration work. Co-authored-by: Cursor <cursoragent@cursor.com>
a7aed5f to
83d89a6
Compare
Move runTurn out of handlers into utils, and drop postgres-js/Docker Postgres in favor of Neon branches with the production neon-http driver. Co-authored-by: Cursor <cursoragent@cursor.com>
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
shared/connections/src/rtc/session.ts (1)
36-47: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winPre-existing
wss://protocol downgrade bug now exposed by export.
normalizeHostmapsurl.protocol === "https:"towssand everything else tows. If a caller passeswss://cyrus.example.com,url.protocoliswss:(nothttps:), so the function returnsprotocol: "ws"— silently downgrading a secure WebSocket URL to insecure. This is a security concern now that the function is exported and part of the public API surface.Consider mapping both
https:andwss:towss:🔒 Proposed fix
export function normalizeHost(host: string): { host: string; protocol: "ws" | "wss"; } { if (host.includes("://")) { const url = new URL(host); return { host: url.host, - protocol: url.protocol === "https:" ? "wss" : "ws", + protocol: url.protocol === "https:" || url.protocol === "wss:" ? "wss" : "ws", }; } return { host, protocol: "ws" }; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/connections/src/rtc/session.ts` around lines 36 - 47, Update normalizeHost to preserve secure WebSocket URLs: map both "https:" and "wss:" protocols to "wss", while mapping only non-secure protocols to "ws". Keep the existing host extraction and return shape unchanged.
🧹 Nitpick comments (4)
shared/database/__tests__/integration/repositories.test.ts (1)
20-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTest creates
/tmp/cyrusdirectory without cleanup.
createProject("Cyrus", "/tmp/cyrus")triggersmkdir("/tmp/cyrus", { recursive: true })insidecreateProject, butwithTempDatabaseonly cleans up the temp DB directory — not the project's cwd. Consider using a path inside the temp directory or an empty cwd to avoid leaving artifacts behind.♻️ Suggested change
- const created = await createProject("Cyrus", "/tmp/cyrus"); + const created = await createProject("Cyrus");Or pass a path under
os.tmpdir()that the test manages itself.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/database/__tests__/integration/repositories.test.ts` around lines 20 - 38, Update the “creates and lists projects” test to avoid using the unmanaged “/tmp/cyrus” path: use an empty cwd or a path created under the temporary directory managed by withTempDatabase, and update the expected cwd accordingly. Keep the existing assertions for project creation and listing.apps/cli/src/utils/run-turn.test.ts (1)
1-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd test coverage for the initial emit failure path.
The two existing tests cover the happy path and streaming failure, but the
started.isErr()branch (initialemitcalls foruser_message/thread_started) is untested. This is the same branch flagged inrun-turn.tswhere no terminal event is emitted. Once that fix is applied, a test verifyingturn_interruptedis emitted on initial emit failure would close the gap.Suggested test for initial emit failure
+ test("emits interrupted terminal event when initial emits fail", async () => { + const terminal: ChatChunk["event"][] = []; + + const result = await runTurn({ + agentName: "claude", + threadId: "thread-1", + projectId: "project-1", + message: "hello", + emit: () => Promise.reject(new Error("emit failed")), + emitTerminal: (event) => { + terminal.push(event); + return Promise.resolve(); + }, + runtime: { + threadCoordinator: { + prompt: () => prompt(), + }, + } as never, + }); + + expect(result.isErr()).toBe(true); + expect(terminal).toEqual([{ type: "turn_interrupted" }]); + });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/cli/src/utils/run-turn.test.ts` around lines 1 - 71, Add a test in the runTurn describe block covering failure of the initial emit calls for user_message or thread_started. Make emit reject with an error, invoke runTurn with the existing required inputs, assert the result is an error, and verify emitTerminal receives a single turn_interrupted event.shared/connections/src/rtc/session.test.ts (1)
4-25: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd test coverage for
wss://andws://protocol inputs.The current tests cover
https://,http://, and bare hosts, but notwss://orws://inputs. Thewss://case would expose the downgrade bug flagged insession.ts. Adding these cases would strengthen the test suite and guard against regressions.🧪 Suggested additional test cases
test("defaults bare hosts to ws", () => { expect(normalizeHost("localhost:8787")).toEqual({ host: "localhost:8787", protocol: "ws", }); }); + + test("parses wss urls as wss", () => { + expect(normalizeHost("wss://cyrus.example.com")).toEqual({ + host: "cyrus.example.com", + protocol: "wss", + }); + }); + + test("parses ws urls as ws", () => { + expect(normalizeHost("ws://localhost:8787")).toEqual({ + host: "localhost:8787", + protocol: "ws", + }); + }); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/connections/src/rtc/session.test.ts` around lines 4 - 25, Add test cases in the normalizeHost suite for wss:// and ws:// inputs, asserting that the host is preserved and protocols remain wss and ws respectively. Use the existing normalizeHost tests as the pattern and ensure the wss:// case prevents protocol downgrading.shared/connections/src/rtc/peer.test.ts (1)
10-39: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueTiming-based assertions with
Bun.sleep(10)may be flaky in CI.Both tests rely on
Bun.sleep(10)to allow async microtask delivery. While 10ms is likely sufficient for synchronous generators, this pattern is inherently timing-dependent. Consider using a deterministic approach — e.g., polling withawait new Promise(r => setTimeout(r, 0))to flush microtasks, or asserting on thereceivedarray after the stream's async iteration has settled via a promise or callback signal.This is a minor concern given the synchronous generator, but worth noting for future tests that may use real async streams.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/connections/src/rtc/peer.test.ts` around lines 10 - 39, Replace the timing-dependent Bun.sleep(10) calls in the “fans out events to subscribers” and “stops delivering after close” tests with deterministic synchronization, such as awaiting a promise/callback that signals async iteration completion or a zero-delay event-loop flush. Ensure assertions run only after delivery has settled while still verifying no events arrive after events.close().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.github/workflows/ci.yml:
- Around line 58-68: Add persist-credentials: false to the checkout step in the
test-integration job to prevent GitHub token persistence, and add needs:
check-types to gate integration tests on successful type checking, matching
test-unit.
In `@apps/cli/src/utils/run-turn.ts`:
- Line 33: When runTurn’s initial emit fails, it returns without notifying the
client, leaving the subscription open. Update the started.isErr() branch in
runTurn to call emitTerminal with a turn_interrupted event before returning the
error, matching the streamed.isErr() handling; preserve the existing error
return.
In `@shared/connections/src/rtc/peer.test.ts`:
- Around line 5-7: Change the eventStream generator to an async generator so it
returns AsyncIterable<ServerEvent> as required by createSignalingEvents,
preserving its existing event iteration behavior.
In `@shared/database/__tests__/helpers/turso.ts`:
- Around line 11-17: Guard the cleanup in the helper’s try/finally block so
connection.close() is only called after a successful connection.open(), or catch
and suppress close errors when opening fails; preserve the original error while
still removing the temporary directory.
---
Outside diff comments:
In `@shared/connections/src/rtc/session.ts`:
- Around line 36-47: Update normalizeHost to preserve secure WebSocket URLs: map
both "https:" and "wss:" protocols to "wss", while mapping only non-secure
protocols to "ws". Keep the existing host extraction and return shape unchanged.
---
Nitpick comments:
In `@apps/cli/src/utils/run-turn.test.ts`:
- Around line 1-71: Add a test in the runTurn describe block covering failure of
the initial emit calls for user_message or thread_started. Make emit reject with
an error, invoke runTurn with the existing required inputs, assert the result is
an error, and verify emitTerminal receives a single turn_interrupted event.
In `@shared/connections/src/rtc/peer.test.ts`:
- Around line 10-39: Replace the timing-dependent Bun.sleep(10) calls in the
“fans out events to subscribers” and “stops delivering after close” tests with
deterministic synchronization, such as awaiting a promise/callback that signals
async iteration completion or a zero-delay event-loop flush. Ensure assertions
run only after delivery has settled while still verifying no events arrive after
events.close().
In `@shared/connections/src/rtc/session.test.ts`:
- Around line 4-25: Add test cases in the normalizeHost suite for wss:// and
ws:// inputs, asserting that the host is preserved and protocols remain wss and
ws respectively. Use the existing normalizeHost tests as the pattern and ensure
the wss:// case prevents protocol downgrading.
In `@shared/database/__tests__/integration/repositories.test.ts`:
- Around line 20-38: Update the “creates and lists projects” test to avoid using
the unmanaged “/tmp/cyrus” path: use an empty cwd or a path created under the
temporary directory managed by withTempDatabase, and update the expected cwd
accordingly. Keep the existing assertions for project creation and listing.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: fce6a678-1b51-4c19-b5e2-fc0fa475484c
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (16)
.github/workflows/ci.ymlapps/cli/package.jsonapps/cli/src/core/acp/events.test.tsapps/cli/src/handlers/controller/chat.tsapps/cli/src/utils/run-turn.test.tsapps/cli/src/utils/run-turn.tsapps/cli/src/utils/streams.test.tsdocs/testing.mdshared/connections/package.jsonshared/connections/src/rtc/peer.test.tsshared/connections/src/rtc/session.test.tsshared/connections/src/rtc/session.tsshared/database/__tests__/helpers/turso.tsshared/database/__tests__/integration/repositories.test.tsshared/database/package.jsonshared/database/tsconfig.json
Emit turn_interrupted on initial emit failure, fix wss:// host normalization, harden test helpers, and align integration CI with unit test job settings. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Addressed CodeRabbit inline review in
Intentionally unchanged (scope):
|
Implements #31
Summary
@cyrus/databaseTurso integration tests with isolated temp databasesrunTurnfrom controller chat handler and add CLI unit coverage@cyrus/connectionssignaling/session unit testscreatePostgresDb()factory anddocker-compose.test.ymlfor future Postgres integrationtest-integrationjobTest plan
bun test:unitbun test:integrationbun check:typesStacked on #35
Closes #31
Part of #29
Summary by CodeRabbit
New Features
Documentation
Chores