Skip to content

Stop relaunching creation-time agents on workspace activation - #10647

Merged
AmethystLiang merged 6 commits into
mainfrom
feature-let-workspaces-opt-out-of-relaunching-th
Jul 28, 2026
Merged

AmethystLiang merged 6 commits into
mainfrom
feature-let-workspaces-opt-out-of-relaunching-th

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Remove the fallback that relaunched createdWithAgent when activating an empty worktree.
  • Keep explicit startup payloads working for callers that intentionally queue a command.
  • Retain createdWithAgent metadata for removal safety, ownership, and preflight instead of reopen behavior.
  • Add activation coverage for repeated close/reopen cycles, post-delete focus handoff, host-originated activation, and explicit startup preservation.
  • Move WSL single-quote launch quoting coverage to direct agent launch tests.

fixes 10578

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Daemon 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only includes a brief summary and issue link; it omits the required Screenshots, Testing, AI Review Report, Security Audit, and Notes sections. Add all template sections, especially testing results, AI review and security summaries, screenshots/no visual change, and any platform-specific notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: preventing activation from relaunching creation-time agents.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feature-let-workspaces-opt-out-of-relaunching-th

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/renderer/src/lib/worktree-activation-created-agent-test-state.ts (1)

30-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting shared boilerplate with seedAlreadyActiveWorktree.

Both seed helpers duplicate the repos array, settings cast, 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 win

Repeated 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1648262 and 6d60952.

📒 Files selected for processing (5)
  • src/renderer/src/lib/launch-agent-in-new-tab.test.ts
  • src/renderer/src/lib/launch-work-item-direct.ts
  • src/renderer/src/lib/worktree-activation-created-agent-test-state.ts
  • src/renderer/src/lib/worktree-activation-created-agent.test.ts
  • src/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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/daemon/ndjson.test.ts (1)

21-26: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover 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 win

Add 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(). Test notify() 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.ts
  • src/main/daemon/client.ts
  • src/main/daemon/daemon-checkpoint-file.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/history-manager-contract.ts
  • src/main/daemon/history-manager.ts
  • src/main/daemon/history-reader.ts
  • src/main/daemon/json-utf8-byte-length.test.ts
  • src/main/daemon/json-utf8-byte-length.ts
  • src/main/daemon/ndjson.test.ts
  • src/main/daemon/ndjson.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-checkpoint-serializer.ts
  • src/main/daemon/terminal-checkpoint-writer-bounds.test.ts
  • src/main/daemon/terminal-history-file-limits.ts
  • src/main/daemon/terminal-history-seed-chunks.test.ts
  • src/main/daemon/terminal-history-seed-chunks.ts
  • src/main/daemon/terminal-history-seed-transfer-protocol.ts
  • src/main/daemon/terminal-history-seed-transfer-registry.test.ts
  • src/main/daemon/terminal-history-seed-transfer-registry.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/terminal-host-session-create.ts
  • src/main/daemon/types.ts
  • src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts
  • src/renderer/src/lib/launch-agent-in-new-tab.test.ts
  • src/renderer/src/lib/launch-work-item-direct.ts
  • src/renderer/src/lib/worktree-activation-created-agent-test-state.ts
  • src/renderer/src/lib/worktree-activation-created-agent.test.ts
  • src/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

Comment thread src/main/daemon/daemon-pty-adapter.ts Resolved
Comment thread src/main/daemon/session.ts Resolved
- 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
@AmethystLiang
AmethystLiang force-pushed the feature-let-workspaces-opt-out-of-relaunching-th branch from c92c66a to 07fe9cd Compare July 28, 2026 20:47
Comment thread src/main/daemon/daemon-pty-adapter.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR removes the fallback that auto-relaunched createdWithAgent when activating an empty worktree, keeping createdWithAgent only for ownership/safety metadata. Alongside that behavioral fix it ships two infrastructure improvements: a chunked seed-transfer protocol (daemon v30) to deliver large cold-restore seeds across bounded NDJSON messages instead of one oversized line, and a bounded checkpoint serializer that binary-searches for the maximum scrollback rows that fit within the 200 MB limit, returning a retryable result rather than disabling the session on failure.

  • Activation change (worktree-activation.ts): buildCreatedAgentReopenStartup and all its imports are deleted; activateAndRevealWorktree now passes only the caller-supplied opts.startup, so no implicit agent launch ever occurs on empty-worktree open.
  • Chunked transfer protocol (terminal-history-seed-transfer-registry.ts, terminal-history-seed-chunks.ts, daemon-server.ts): four new RPC messages with per-owner isolation, SHA-256 integrity, TTL expiry, and graceful fallback to seed-unavailable on old daemons (protocol < 30).
  • Bounded checkpoint (terminal-checkpoint-serializer.ts, terminal-history-session-writer.ts): replays the snapshot through HeadlessEmulator when direct serialization exceeds the byte cap, then binary-searches for the largest scrollback window that fits; historySeedUnavailable flag scoped per createOrAttach call to prevent bleed across the aliveness-probe retry.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

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.
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolved

1 similar comment
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolved

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks for resolving this.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks for resolving this.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@AmethystLiang
AmethystLiang merged commit ca5a821 into main Jul 28, 2026
32 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
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.

1 participant