Repository navigation
Stop relaunching creation-time agents on workspace activation - #10647
Conversation
📝 WalkthroughWalkthroughDaemon terminal history now supports bounded checkpoint serialization, checkpoint outcome propagation, parser-tail metadata, Unicode-safe seed chunking, and authenticated chunked history transfer with protocol routing and cleanup. NDJSON requests enforce encoded line limits, while notifications tolerate write failures. Worktree activation no longer derives startup payloads from persisted agent metadata; explicit startup remains supported, with expanded activation tests and WSL single-quote escaping coverage. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
⚔️ Resolve merge conflicts
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 |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/renderer/src/lib/worktree-activation-created-agent-test-state.ts (1)
30-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting shared boilerplate with
seedAlreadyActiveWorktree.Both seed helpers duplicate the
reposarray,settingscast, and several field initializations. A small shared base-state builder would reduce duplication as the store shape evolves.src/renderer/src/lib/worktree-activation-created-agent.test.ts (1)
112-171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRepeated seed/activate/assert pattern across the four new tests.
Each of the four tests repeats the same "seed → activate → assert tabId defined and pendingStartupByTabId" shape. A small shared assertion helper (e.g.,
activateAndExpectNoRelaunch(worktreeId, opts?)) would cut duplication.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0bfc8768-df11-42b0-b96c-3743b65778a6
📒 Files selected for processing (5)
src/renderer/src/lib/launch-agent-in-new-tab.test.tssrc/renderer/src/lib/launch-work-item-direct.tssrc/renderer/src/lib/worktree-activation-created-agent-test-state.tssrc/renderer/src/lib/worktree-activation-created-agent.test.tssrc/renderer/src/lib/worktree-activation.ts
…e activation Activating a workspace with zero renderable tabs launched the agent it was created with, unprompted and in approval-bypass mode. Navigation is not consent to start a process: the same fallback fired from post-delete focus handoff, the jump palette, keyboard cycling, CLI/relay activation, and notification clicks. The mechanism was superseded. #1814 added it when relaunching the created agent *was* the resume feature; #4706 later added real provider-session resume six lines above and left the fallback in place. What remained fired whenever a workspace had no renderable tabs -- including when nothing had ever slept -- and reported itself as `request_kind: 'resume'` while resuming nothing, discarding any resumable session a plain tab close had already purged. No caller depends on it. All seven intent-carrying callers pass an explicit `startup` on the branch where they intend a launch, and every no-startup branch either declined an agent, already has one running (host `didSpawnStartup`), or is this same defect arriving over IPC. Drops the now-orphaned imports, retargets the stale comment in launch-work-item-direct that cited reopen-relaunch as the reason to persist `createdWithAgent`, and moves the WSL default-args quoting assertion to launch-agent-in-new-tab, whose launch path still resolves those args. Regression tests are revert-sensitive -- all four fail if the fallback returns.
…reach Three tests were named after scenarios they never invoked, which is the failure mode that lets a coverage gap read as closed. - The "host-originated" test's `notifyHostRuntime: false` is inert here: both gates resolve through `isWebRuntimeSessionActive`, false with no runtime environment seeded, so it was byte-identical to the plain reopen test. It no longer claims to cover the host `didSpawnStartup` leg, which lives in main and is unreachable from this layer. - The "post-delete focus handoff" test never deleted anything and never touched `prepareActiveWorktreeFocusAfterDelete`. That caller is asserted directly in active-worktree-focus-after-delete.test.ts, which locks out any opts. - The activate/close loop resets state instead of calling `closeTab`, so it does not exercise the sleeping-record purge its comment claimed. Also folds the primary reopen test onto `seedEmptyActivatableWorktree` — the fixture extracted for exactly that state, which its inline copy had drifted from by hardcoding a POSIX repo path. `preflight` is dropped from the launch-work-item-direct comment: the trust preflight reads the create-time argument (worktree-remote.ts), not the persisted meta. Removal safety and ownership do read the field and remain accurate. Renames the ported quoting test to what it pins. Under vitest's node environment `navigator.userAgent` carries no "Windows", so platform resolution bails before the WSL branch and the WSL preference is inert — the real coverage is single-quote escaping of user-configured agentDefaultArgs.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/main/daemon/ndjson.test.ts (1)
21-26: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCover multibyte UTF-8 payloads.
This test only uses ASCII, so an implementation that incorrectly counts characters instead of UTF-8 bytes would still pass. Add a boundary case using
éor an emoji.src/main/daemon/client.ts (1)
220-231: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a regression test for notification failures.
The new behavior intentionally suppresses both oversized-encoding and synchronous socket-write errors, but the added tests only cover
request(). Testnotify()with an oversized payload and a throwing socket.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a9b0eb14-99d6-4d19-b336-c8efa0016333
📥 Commits
Reviewing files that changed from the base of the PR and between 6d60952 and c92c66a9fb882356c90eac65b46da57106d61921.
📒 Files selected for processing (32)
src/main/daemon/client.test.tssrc/main/daemon/client.tssrc/main/daemon/daemon-checkpoint-file.tssrc/main/daemon/daemon-protocol-version.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-server.tssrc/main/daemon/history-manager-contract.tssrc/main/daemon/history-manager.tssrc/main/daemon/history-reader.tssrc/main/daemon/json-utf8-byte-length.test.tssrc/main/daemon/json-utf8-byte-length.tssrc/main/daemon/ndjson.test.tssrc/main/daemon/ndjson.tssrc/main/daemon/session.tssrc/main/daemon/terminal-checkpoint-serializer.tssrc/main/daemon/terminal-checkpoint-writer-bounds.test.tssrc/main/daemon/terminal-history-file-limits.tssrc/main/daemon/terminal-history-seed-chunks.test.tssrc/main/daemon/terminal-history-seed-chunks.tssrc/main/daemon/terminal-history-seed-transfer-protocol.tssrc/main/daemon/terminal-history-seed-transfer-registry.test.tssrc/main/daemon/terminal-history-seed-transfer-registry.tssrc/main/daemon/terminal-host-create-contract.tssrc/main/daemon/terminal-host-session-create.tssrc/main/daemon/types.tssrc/renderer/src/hooks/useComposerState-host-context-boundaries.test.tssrc/renderer/src/lib/launch-agent-in-new-tab.test.tssrc/renderer/src/lib/launch-work-item-direct.tssrc/renderer/src/lib/worktree-activation-created-agent-test-state.tssrc/renderer/src/lib/worktree-activation-created-agent.test.tssrc/renderer/src/lib/worktree-creation-flow.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/renderer/src/lib/launch-work-item-direct.ts
- src/renderer/src/lib/launch-agent-in-new-tab.test.ts
- src/renderer/src/lib/worktree-activation-created-agent-test-state.ts
- Oversized cold-restore snapshots (>1MB) now upload via chunked startHistorySeedTransfer/appendHistorySeedTransfer protocol instead of inline, avoiding NDJSON line-size violations - Checkpoints automatically trim oldest rows to fit within configured byte limit (200MB) before commit - Protocol v30 required for chunked transfers; v29 daemons gracefully fall back to renderer-only recovery - NDJSON encodeNdjson() validates line size and rejects oversized payloads; notifications silently swallow encoding errors
c92c66a to
07fe9cd
Compare
Greptile SummaryThis PR removes the fallback that auto-relaunched
Confidence Score: 5/5Safe to merge — the activation change is a clean deletion with comprehensive regression tests, and the new chunked transfer infrastructure is well-guarded with integrity checks, TTL cleanup, and legacy-daemon fallback. The activation removal is a straightforward deletion of ~50 lines tested for all key paths (empty worktree, repeated cycles, sibling handoff, explicit startup preserved). The chunked seed protocol is narrow in scope with each layer having its own tests, SHA-256 end-to-end integrity verification, and a fallback that ensures old daemons are not broken. The bounded checkpoint serializer correctly falls back to retryable rather than disabling the session, and the existing checkpointInFlight guard serializes concurrent checkpoint calls so the new async replay path does not introduce races. Files Needing Attention: No files require special attention. The most complex new file is terminal-checkpoint-serializer.ts, but it is covered by the bounded-writer bounds tests.
|
| Filename | Overview |
|---|---|
| src/renderer/src/lib/worktree-activation.ts | Removes buildCreatedAgentReopenStartup and all its imports; activateAndRevealWorktree now passes only the caller-supplied startup, never a synthetic creation-time relaunch. |
| src/main/daemon/daemon-pty-adapter.ts | historySeedUnavailable is now scoped per createOrAttach invocation (fixing the flag-bleed noted in previous review); large seeds routed through the new chunked transfer protocol; takeSnapshotAndCheckpoint propagates HistoryCheckpointResult and defers retryable failures. |
| src/main/daemon/terminal-history-seed-transfer-registry.ts | New registry: enforces MAX_TRANSFERS, MAX_CHUNKS, SHA-256 integrity, byte budget, per-owner isolation, 30 s TTL, and clearOwner/dispose for lifecycle. |
| src/main/daemon/terminal-checkpoint-serializer.ts | New serializer: tries direct JSON first; if over limit, replays snapshot through HeadlessEmulator and binary-searches maximum scrollback rows that still fit within the byte cap. |
| src/main/daemon/daemon-server.ts | Adds four new request handlers for the seed-transfer protocol; clears owned transfers on client disconnect/reconnect; rejects both historySeed and historySeedTransferId being set simultaneously. |
| src/main/daemon/history-manager.ts | checkpoint() now returns HistoryCheckpointResult; mutation tracking extracted to TerminalHistoryMutationTracker; checkpointMaxBytes injected so bounds tests can use a small limit. |
| src/main/daemon/ndjson.ts | encodeNdjson now throws NdjsonLineTooLongError when the encoded line exceeds 16 MB; notify() catches it; request() lets it propagate synchronously (caught by await at call sites). |
| src/main/daemon/json-utf8-byte-length.ts | New fast estimator for JSON UTF-8 byte size used to pre-check checkpoint fits before JSON.stringify; handles all JS value types, surrogates, control characters, and circular-reference detection. |
| src/main/daemon/terminal-history-session-writer.ts | checkpoint() delegates to serializeTerminalCheckpointWithinLimit; returns committed/retryable result; session not disabled on retryable failure, preserving the old checkpoint file. |
| src/shared/local-build-compatibility-contract.json | Protocol version bumped to 30; v29 added to attachable list; matches daemon-protocol-version.ts constants. |
Sequence Diagram
sequenceDiagram
participant R as Renderer
participant A as DaemonPtyAdapter
participant S as DaemonServer
participant Reg as SeedTransferRegistry
participant H as Host (PTY)
R->>A: "spawn({ sessionId, ... })"
A->>A: getRecoveredHistorySeedSegments(restoreInfo)
alt "seed <= 1M code units (inline)"
A->>S: "createOrAttach({ historySeed })"
else "seed > 1M and protocolVersion >= 30"
A->>S: startHistorySeedTransfer(manifest)
S->>Reg: start(clientId, manifest)
Reg-->>S: transferId
S-->>A: "{ transferId }"
loop each 512K chunk
A->>S: "appendHistorySeedTransfer({ transferId, index, data })"
S->>Reg: append(clientId, transferId, index, data)
end
A->>S: "finishHistorySeedTransfer({ transferId })"
S->>Reg: finish — validates SHA-256
A->>S: "createOrAttach({ historySeedTransferId })"
S->>Reg: take(clientId, transferId)
Reg-->>S: chunks[]
S->>H: "createOrAttach({ historySeedChunks })"
else "seed > 1M and protocolVersion < 30"
A->>S: "createOrAttach({}) — seed unavailable"
end
S-->>A: CreateOrAttachResult
A-->>R: PtySpawnResult
Reviews (3): Last reviewed commit: "Bump daemon protocol version to 30" | Re-trigger Greptile
When a final snapshot checkpoint fails to serialize (returns retryable), the pending output records must not be appended later—doing so would splice them over the seq gap left by the failed snapshot, defeating gap detection. Drop the records and retry the checkpoint instead.
|
@coderabbitai[bot] resolved |
1 similar comment
|
@coderabbitai[bot] resolved |
|
Tip For best results, initiate chat on the files or code changes.
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
|
Tip For best results, initiate chat on the files or code changes.
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
…ai#10647) * fix(activation): stop relaunching the creation-time agent on workspace activation Activating a workspace with zero renderable tabs launched the agent it was created with, unprompted and in approval-bypass mode. Navigation is not consent to start a process: the same fallback fired from post-delete focus handoff, the jump palette, keyboard cycling, CLI/relay activation, and notification clicks. The mechanism was superseded. stablyai#1814 added it when relaunching the created agent *was* the resume feature; stablyai#4706 later added real provider-session resume six lines above and left the fallback in place. What remained fired whenever a workspace had no renderable tabs -- including when nothing had ever slept -- and reported itself as `request_kind: 'resume'` while resuming nothing, discarding any resumable session a plain tab close had already purged. No caller depends on it. All seven intent-carrying callers pass an explicit `startup` on the branch where they intend a launch, and every no-startup branch either declined an agent, already has one running (host `didSpawnStartup`), or is this same defect arriving over IPC. Drops the now-orphaned imports, retargets the stale comment in launch-work-item-direct that cited reopen-relaunch as the reason to persist `createdWithAgent`, and moves the WSL default-args quoting assertion to launch-agent-in-new-tab, whose launch path still resolves those args. Regression tests are revert-sensitive -- all four fail if the fallback returns. * test(activation): name the relaunch regression tests after what they reach Three tests were named after scenarios they never invoked, which is the failure mode that lets a coverage gap read as closed. - The "host-originated" test's `notifyHostRuntime: false` is inert here: both gates resolve through `isWebRuntimeSessionActive`, false with no runtime environment seeded, so it was byte-identical to the plain reopen test. It no longer claims to cover the host `didSpawnStartup` leg, which lives in main and is unreachable from this layer. - The "post-delete focus handoff" test never deleted anything and never touched `prepareActiveWorktreeFocusAfterDelete`. That caller is asserted directly in active-worktree-focus-after-delete.test.ts, which locks out any opts. - The activate/close loop resets state instead of calling `closeTab`, so it does not exercise the sleeping-record purge its comment claimed. Also folds the primary reopen test onto `seedEmptyActivatableWorktree` — the fixture extracted for exactly that state, which its inline copy had drifted from by hardcoding a POSIX repo path. `preflight` is dropped from the launch-work-item-direct comment: the trust preflight reads the create-time argument (worktree-remote.ts), not the persisted meta. Removal safety and ownership do read the field and remain accurate. Renames the ported quoting test to what it pins. Under vitest's node environment `navigator.userAgent` carries no "Windows", so platform resolution bails before the WSL branch and the WSL preference is inert — the real coverage is single-quote escaping of user-configured agentDefaultArgs. * transfer large terminal history seeds across bounded protocol messages - Oversized cold-restore snapshots (>1MB) now upload via chunked startHistorySeedTransfer/appendHistorySeedTransfer protocol instead of inline, avoiding NDJSON line-size violations - Checkpoints automatically trim oldest rows to fit within configured byte limit (200MB) before commit - Protocol v30 required for chunked transfers; v29 daemons gracefully fall back to renderer-only recovery - NDJSON encodeNdjson() validates line size and rejects oversized payloads; notifications silently swallow encoding errors * fix(daemon): drop held output when teardown checkpoint fails to serializ When a final snapshot checkpoint fails to serialize (returns retryable), the pending output records must not be appended later—doing so would splice them over the seq gap left by the failed snapshot, defeating gap detection. Drop the records and retry the checkpoint instead. * Bump daemon protocol version to 30 * Bump daemon protocol version to 30
Summary
createdWithAgentwhen activating an empty worktree.createdWithAgentmetadata for removal safety, ownership, and preflight instead of reopen behavior.fixes 10578