Skip to content

Add native Grok Vault resume support - #4398

Merged
austinywang merged 15 commits into
mainfrom
issue-4394-grok-vault-resume
May 20, 2026
Merged

austinywang merged 15 commits into
mainfrom
issue-4394-grok-vault-resume

Conversation

@austinywang

@austinywang austinywang commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4394

Summary

  • Register Grok as a built-in Vault agent and index native ~/.grok/sessions/<encoded-cwd>/<session>/chat_history.jsonl history.
  • Wire Grok hook session IDs into the existing surface resume path with grok -r <id>.
  • Add a bundled grok wrapper plus shell integration so cmux launches install Grok hooks automatically.
  • Add regression coverage for native Grok Vault loading and Grok hook resume binding publication.

Verification

  • Not run: local build/test commands are intentionally skipped per HQ instruction.
  • Ran static checks only: git diff --check, plutil -lint cmux.xcodeproj/project.pbxproj, bash -n Resources/bin/grok, bash -n Resources/shell-integration/cmux-bash-integration.bash, zsh -n Resources/shell-integration/cmux-zsh-integration.zsh.

View in Codesmith
Need help on this PR? Tag @codesmith with what you need.

  • Let Codesmith autofix CI failures and bot reviews

Note

Medium Risk
Adds new Grok session discovery/resume paths plus bundled shell wrappers, which can affect session search results and CLI launch behavior (PATH/hook installation) across users’ environments.

Overview
Adds native Grok Vault support: registers Grok as a built-in Vault agent and indexes ~/.grok/sessions/<encoded-cwd>/<session>/chat_history.jsonl (including GROK_HOME-scoped roots and hook-observed homes) to enable Grok sessions to appear in search and be resumed.

Updates resume + transcript handling for Grok and Grok-compatible registered agents: builds grok -r <sessionId> resume commands with safer single-quoted argv/env formatting, adds Grok-specific transcript role inference/layout, and introduces a new grokSessionDirectory sessionIdSource plus multi-name process detection.

Bundles a grok CLI wrapper and extends bash/zsh shell integration to install both claude and grok wrappers, enabling automatic Grok hook installation and launch metadata capture; adds a Grok icon asset and expands test coverage for Grok loading and resume binding behavior.

Reviewed by Cursor Bugbot for commit 12ae177. Bugbot is set up for automated code reviews on this repo. Configure here.


Summary by cubic

Adds native Grok Vault indexing, search, and one‑command resume for the built‑in grok agent and Grok‑compatible registered agents. Also scopes Grok agent searches to the current directory, adds a Grok icon, improves title extraction, honors GROK_HOME and custom hook state dirs, deduplicates sessions, and preserves GROK_HOME in resume commands. Fixes #4394.

  • New Features

    • Register grok as a built‑in Vault agent; detect grok, grok-macos-aarch64, and grok-macos-aarch; honor GROK_HOME.
    • Filesystem loader: index ~/.grok/sessions/<encoded-cwd>/<session>/chat_history.jsonl; de‑dupe across roots and encoded CWD variants; include sessions from hook‑observed homes; honor CMUX_AGENT_HOOK_STATE_DIR.
    • Resume: build single‑quoted grok -r <id> commands and carry GROK_HOME for both built‑in and registered grokSessionDirectory agents.
    • Bundle Resources/bin/grok and a unified bash/zsh wrapper installer for both claude and grok; auto‑install hooks only for chat‑like runs; allow hook setup to create the config dir when missing.
    • Transcript previews: apply the Grok layout and broaden role/type detection (assistant/user/system/tool) for built‑in and registered Grok sessions.
    • UI: add a Grok agent icon and map it to the built‑in agent.
  • Bug Fixes

    • Harden Grok resume option parsing for -r/--resume, including = forms.
    • Quote env and argv with single quotes to handle spaces and special characters.
    • Improve process matching by allowing multiple executable names in detection rules.
    • Fix Grok Vault titles: prefer the user’s prompt and strip injected metadata tags from previews.
    • Fix Grok agent‑scoped Vault filtering to respect the current directory (CWD).

Written for commit 12ae177. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

  • New Features

    • Grok sessions discovery across encoded project directories and reliable resume handling
    • Built-in Grok agent registration and improved process/session detection
    • Grok CLI wrapper that exports launch metadata and auto-installs hooks when appropriate
    • Transcript preview parsing updated to recognize Grok layouts and infer roles
    • Resume command formatting preserves quoted argv/env tokens
  • Refactor

    • Generic Bash/Zsh installer for CLI wrappers (now installs grok and claude)
  • Tests

    • New integration and unit tests for Grok hooks, resume flow, and session persistence

Review Change Stack

@vercel

vercel Bot commented May 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
cmux Ready Ready Preview, Comment May 20, 2026 8:30am
cmux-staging Building Building Preview, Comment May 20, 2026 8:30am

@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Grok as a built-in Vault agent: registry + detect rules, a Bash grok wrapper that installs cmux hooks and exports launch metadata, shell integrations, Grok session discovery from chat_history.jsonl (with CWD encoding), CLI resume wiring, transcript parsing tweaks, and related tests.

Changes

Grok Vault Agent Integration

Layer / File(s) Summary
Grok registration and session-ID source contract
Sources/VaultAgentRegistry.swift, Sources/RestorableAgentTypes.swift
CmuxVaultAgentRegistration.builtInGrok and grokSessionDirectory added; detect rule accepts processNames; small RestorableAgentTypes comment update.
Grok wrapper script and shell integration
Resources/bin/grok, Resources/shell-integration/cmux-bash-integration.bash, Resources/shell-integration/cmux-zsh-integration.zsh, cmux.xcodeproj/project.pbxproj
Bash wrapper locates real grok, conditionally installs hooks via cmux socket, exports CMUX_AGENT_LAUNCH_*, then execs real grok; bash/zsh integrations install shell wrapper functions; Xcode project includes the grok script.
CLI grok resume command switch
CLI/cmux.swift
New "grok" CLI branch resumes via agentSurfaceResumeWithOption(..., fallbackExecutable: "grok", option: "-r"); adds helpers for encoded CWD variants and history mod-date selection.
Grok session locator and entry loading
Sources/SessionIndexRegisteredAgents.swift
GrokSessionLocator computes sessions roots (GROK_HOME, encoded CWDs), enumerates chat_history.jsonl, optionally ripgrep-prefilters needle, extracts Grok JSONL metadata, and builds .grok SessionEntry records.
Session store and process scanner integration
Sources/SessionIndexStore.swift, Sources/VaultAgentProcessScanner.swift
searchSessions/searchAgent route .grok to vault-backed registry and loadGrokEntries(...); process scanner parses -r/--resume argv forms for Grok session IDs.
Grok transcript role detection
Sources/SessionIndexView.swift
Adds grokRoleNeedles, uses type and role fields to infer assistant/user for Grok, and isolates Grok-specific role inference.
Resume command tokenization
Sources/SessionIndexModels.swift
Resume command now built from argv tokens with GROK_HOME env assignments and single-quote tokenization helpers.
Grok integration and unit tests
cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift, cmuxTests/PiVaultAgentPersistenceTests.swift, cmuxTests/SessionIndexViewTests.swift
Integration test verifies surface.resume.set published with GROK_HOME and native resume; unit tests validate builtInGrok registration, chat history decoding/resumeCommand, registered layout, and CWD-filtered discovery; updated resumeCommand expectation for tokenized quoting.

Sequence Diagram(s)

sequenceDiagram
  participant Shell
  participant GrokWrapper as grok wrapper
  participant CMux
  participant RealGrok as real grok
  Shell->>GrokWrapper: grok [args]
  GrokWrapper->>GrokWrapper: find real grok in PATH
  GrokWrapper->>GrokWrapper: detect CMUX_SURFACE_ID / socket
  alt In cmux environment
    GrokWrapper->>CMux: ping CMUX_SOCKET_PATH
    CMux-->>GrokWrapper: pong
    GrokWrapper->>CMux: hooks grok prompt-submit (install)
    CMux-->>GrokWrapper: install result
    GrokWrapper->>GrokWrapper: export CMUX_AGENT_LAUNCH_*
  end
  GrokWrapper->>RealGrok: exec real grok with original args + env
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

🐰 I found a grok beneath the log,

Hooks stitched tidy by a nimble frog,
Sessions shelved where rabbits browse,
Resume springs up with confident vows,
Hooray — the vault now holds the grok!


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (2 errors, 1 warning)

Check name Status Explanation Resolution
Cmux Swift Blocking Runtime ❌ Error PR introduces 2 Task.sleep calls in production code: 200ms debounce in SessionIndexView.swift and 60s auto-cleanup in SessionIndexStore.swift, both violating the swift-blocking-runtime rule. Replace Task.sleep debounce with proper async sequence/cancellation; replace auto-expire with Timer or scheduled cleanup mechanism.
Cmux Swift @Concurrent ❌ Error New nonisolated async functions perform file I/O (enumeration, parsing, scanning) called from @MainActor context without @concurrent or explicit actor hop. Add @concurrent to loadGrokEntries/loadRegisteredAgentEntries or wrap file-I/O in Task.detached to prevent MainActor blocking.
Docstring Coverage ⚠️ Warning Docstring coverage is 2.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (14 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add native Grok Vault resume support' directly and specifically describes the main change: implementing Vault integration and resume support for Grok.
Linked Issues check ✅ Passed All primary objectives from issue #4394 are met: Grok registered as built-in Vault agent [VaultAgentRegistry], native session indexing from ~/.grok/sessions implemented [SessionIndexRegisteredAgents, SessionIndexStore], resume pipeline wired with grok -r support [SessionIndexModels, CLI/cmux.swift], hooks auto-installation via bundled wrapper [Resources/bin/grok], and test coverage added [PiVaultAgentPersistenceTests, CLINotifyProcessIntegrationRegressionTests].
Out of Scope Changes check ✅ Passed All changes directly support Grok Vault integration and resume: agent registration, session discovery/parsing, resume wiring, wrapper/hook auto-installation, transcript parsing, and tests. Shell integration refactoring (claude/grok wrappers) is in-scope infrastructure for hook auto-installation.
Cmux Swift Actor Isolation ✅ Passed New types follow Swift 6 isolation rules: Sendable types explicitly marked; nonisolated async functions; MainActor-only types properly scoped; no unsafe Sendable or implicit MainActor violations.
Cmux No Hacky Sleeps ✅ Passed No hacky sleeps introduced. Resources/bin/grok contains no bash sleep() calls; CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC are request timeouts. Shell integration changes are pure refactoring.
Cmux Swift Concurrency ✅ Passed SessionIndexRegisteredAgents.swift uses async/await with Task.isCancelled. No DispatchQueue.global, Combine, or completion handlers. AppKit drag/drop DispatchQueue.main.async already present.
Cmux Swift File And Package Boundaries ✅ Passed SessionIndexRegisteredAgents is existing file with cohesive Grok responsibility. SessionIndexView +188 lines under 250-line threshold. No new oversized files created with mixed responsibilities.
Cmux Swift Logging ✅ Passed PR introduces no Swift logging violations: production code uses Apple unified logging properly; print statements in CLI are command outputs (allowed); bash script error message is legitimate.
Cmux User-Facing Error Privacy ✅ Passed No violations. Only user output is generic "Error: grok not found in PATH". GROK_HOME is documented config override like CODEX_HOME. No credentials, tokens, raw errors, or sensitive details exposed.
Cmux Full Internationalization ✅ Passed PR adds Grok agent exactly like existing Pi: hardcoded name in VaultAgentRegistry, no String(localized:), no new localization keys, no xcstrings modified. Follows established pattern.
Cmux Swiftui State Layout ✅ Passed PR introduces no new SwiftUI state (@Observable/@Published/@StateObject). Only existing legacy ObservableObject classes touched incidentally; new code is data loaders and models only.
Cmux Architecture Rethink ✅ Passed PR adds Grok Vault support via stateless helpers and nonisolated async functions without new timing patterns, mutable state, observers, or duplicate wiring.
Cmux Swift Auxiliary Window Close Shortcuts ✅ Passed PR adds no NSWindow, NSPanel, NSWindowController, or SwiftUI Window/WindowGroup code to main sources; only test fixtures which are explicitly allowed by the rule.
Description check ✅ Passed The PR description covers all required sections: summary with what changed and why, verification details, and a checklist of testing and review items.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-4394-grok-vault-resume

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 and usage tips.

Comment thread Sources/SessionIndexStore.swift Outdated
Comment thread Sources/VaultAgentRegistry.swift
Comment thread Sources/SessionIndexRegisteredAgents.swift
coderabbitai[bot]
coderabbitai Bot previously requested changes May 19, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 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 `@Sources/SessionIndexRegisteredAgents.swift`:
- Around line 34-38: Canonicalize the working directory path (normalize ., ..,
trailing slashes and resolve symlinks) before encoding and after decoding so
equivalent paths map to the same folder: update
workingDirectory(fromProjectDirectoryName:) to produce a standardized path
(e.g., use URL(fileURLWithPath:).standardized.path or
FileManager.stringByResolvingSymlinksInPath then standardized) instead of just
trimming, and apply the same normalization in the places that call
encodedSessionCWD(...) and when decoding its result (affecting the code around
encodedSessionCWD, latestSessionId, and the other helper usages noted) so
encoding/decoding uses the canonical form consistently.
- Around line 325-327: When registration.sessionIdSource ==
.grokSessionDirectory you must derive native sessionId and cwd from
GrokSessionLocator.sessionRoots instead of falling back to candidate.url.path;
update the registered-agent path that builds the Published/RegisteredAgent
(where it currently uses candidate.url.path) to call
GrokSessionLocator.sessionRoots(registration: registration, cwdFilter:
cwdFilter), take the matched sessionsRoot entry, set sessionId to the native ID
returned by that locator and set cwd to the sessionsRoot path (or its .path
component) so resume (-r) and publishing use the native session identifier;
apply the same change in the other branch noted (around the 432-433 area) so
both code paths use GrokSessionLocator.sessionRoots results for sessionId and
cwd.

In `@Sources/SessionIndexView.swift`:
- Around line 1411-1415: transcriptRole(from:) returns .event for unknown roles
which is masking Grok's type fallback; change the role selection so that a
.event result from transcriptRole(from: object["role"] as? String) is treated as
"no explicit role" (nil) and allows grokTypeRole (from object["type"]) and
fallbackRole to be used; specifically update the logic around grokTypeRole and
the guard that sets role so that you first get an explicitRole =
transcriptRole(from: object["role"] as? String) and if explicitRole == .event
then use nil, then let role = explicitRole ?? grokTypeRole ?? fallbackRole
before returning.

In `@Sources/VaultAgentProcessScanner.swift`:
- Around line 792-803: In the .grokSessionDirectory branch do not
unconditionally call
GrokSessionLocator.latestSessionId(cwd:registration:environment:fileManager:);
first detect whether multiple live Grok processes share the same cwd (e.g.,
enumerate running processes and match by executable/name and
CMUX_AGENT_LAUNCH_CWD/PWD or similar environment markers) and only perform the
cwd-only fallback when exactly one Grok process is tied to that cwd; if more
than one is found, avoid returning the newest session ID (return nil / require
explicit -r/--resume) so separate panels do not collapse onto the same session.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8882c137-9b07-4847-bdf1-cb749e9b30fc

📥 Commits

Reviewing files that changed from the base of the PR and between c6db818 and 5708d67.

📒 Files selected for processing (13)
  • CLI/cmux.swift
  • Resources/bin/grok
  • Resources/shell-integration/cmux-bash-integration.bash
  • Resources/shell-integration/cmux-zsh-integration.zsh
  • Sources/RestorableAgentTypes.swift
  • Sources/SessionIndexRegisteredAgents.swift
  • Sources/SessionIndexStore.swift
  • Sources/SessionIndexView.swift
  • Sources/VaultAgentProcessScanner.swift
  • Sources/VaultAgentRegistry.swift
  • cmux.xcodeproj/project.pbxproj
  • cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift
  • cmuxTests/PiVaultAgentPersistenceTests.swift

Comment thread Sources/SessionIndexRegisteredAgents.swift
Comment thread Sources/SessionIndexRegisteredAgents.swift
Comment thread Sources/SessionIndexView.swift Outdated
Comment thread Sources/VaultAgentProcessScanner.swift Outdated

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 13 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread Resources/shell-integration/cmux-bash-integration.bash Outdated
Comment thread Sources/VaultAgentProcessScanner.swift
Comment thread Sources/SessionIndexView.swift Outdated
coderabbitai[bot]
coderabbitai Bot previously requested changes May 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@cmuxTests/PiVaultAgentPersistenceTests.swift`:
- Around line 460-463: The test exposes inconsistent shell-quoting: built-in
Grok resume command in PiVaultAgentPersistenceTests compares an unquoted
executable/flags while registered agents use quoted components; inspect the
resumeShellCommand implementation (AgentResumeCommandBuilder or any
Grok-specific resume builder) and ensure all filesystem- or user-derived
components (executable names, arguments, env values) use SessionEntry.shellQuote
consistently; update the Grok path/executable branch so it quotes the executable
and argument tokens the same way as registered-agent code (or centralize quoting
in AgentResumeCommandBuilder/resumeShellCommand) and adjust tests to expect the
consistently-quoted form.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 687d403f-19e2-4279-bd1d-aa30ebc6fd00

📥 Commits

Reviewing files that changed from the base of the PR and between 5708d67 and 7c252d2.

📒 Files selected for processing (7)
  • CLI/cmux.swift
  • Sources/SessionIndexRegisteredAgents.swift
  • Sources/SessionIndexStore.swift
  • Sources/SessionIndexView.swift
  • Sources/VaultAgentProcessScanner.swift
  • Sources/VaultAgentRegistry.swift
  • cmuxTests/PiVaultAgentPersistenceTests.swift

Comment thread cmuxTests/PiVaultAgentPersistenceTests.swift
coderabbitai[bot]
coderabbitai Bot previously requested changes May 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@Sources/SessionIndexView.swift`:
- Around line 1479-1485: The current logic lets transcriptRole(from:)'s fallback
of .event short-circuit later payload/message fallback; change the role
selection so that when roleFromType == .event you only accept it if the raw type
string actually equals "event" (case-insensitive) — otherwise treat roleFromType
as nil so parsedRole / payload/message fallback can run; update the block using
shouldUseGrokTypeRole, transcriptRole(from:), roleFromType, parsedRole and
fallbackRole to implement this check (i.e., only use roleFromType if it's
non-.event or the raw type string is literally "event").
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c69d078f-0840-494e-8c36-6e07d09484b1

📥 Commits

Reviewing files that changed from the base of the PR and between 7c252d2 and bbd65fd.

📒 Files selected for processing (3)
  • Resources/shell-integration/cmux-bash-integration.bash
  • Resources/shell-integration/cmux-zsh-integration.zsh
  • Sources/SessionIndexView.swift

Comment thread Sources/SessionIndexView.swift
Comment thread Sources/SessionIndexRegisteredAgents.swift
coderabbitai[bot]
coderabbitai Bot previously requested changes May 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@cmuxTests/SessionIndexViewTests.swift`:
- Around line 134-137: The test asserts for Claude's resumeCommand use
traditional shell syntax while Grok and other tests expect tokenized format;
update the two Claude assertions (the XCTAssertEqual calls around the earlier
Claude checks) to compare entry.resumeCommand against the tokenized form (e.g.,
each token individually quoted like 'env' 'VAR=value' 'command' ...) so they
match the Grok assertion style and SessionPersistenceTests examples, ensuring
you update the expected strings used in those XCTAssertEqual comparisons for the
Claude entries referenced in this test class.

In `@Sources/SessionIndexView.swift`:
- Around line 1082-1089: The grok role detection is currently limited to only
"user" and "assistant" so lines with type: "system", "developer", or tool-like
types are dropped; update shouldParseRawLine(...) and inferredGrokRole(...) to
mirror the broader set used by parseGenericMessage(...) (and
transcriptRole(from:)), including checks for "system", "developer", "tool_use"
and any other tool-like role strings you support, and also add those
corresponding Data needles to grokRoleNeedles if needed so the oversized-record
placeholder path stays consistent with transcriptRole(from:).
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: edf07089-2683-45b4-9032-9b179cde5d84

📥 Commits

Reviewing files that changed from the base of the PR and between bbd65fd and d7f0bb5.

📒 Files selected for processing (5)
  • Sources/SessionIndexModels.swift
  • Sources/SessionIndexRegisteredAgents.swift
  • Sources/SessionIndexView.swift
  • cmuxTests/PiVaultAgentPersistenceTests.swift
  • cmuxTests/SessionIndexViewTests.swift

Comment thread cmuxTests/SessionIndexViewTests.swift
Comment thread Sources/SessionIndexView.swift Outdated

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1 issue found across 11 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread Sources/SessionIndexView.swift
@greptile-apps

greptile-apps Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Registers Grok as a built-in Vault agent and wires up the full session-discovery, search, preview, and one-command resume pipeline. The previously-flagged CWD-filter discard bug (scopedCwd overwritten to nil before being passed to loadGrokEntries) is fixed in this PR and is covered by testGrokAgentSearchScopeUsesCurrentDirectoryCWDFilter.

  • Native Vault indexing: GrokSessionLocator discovers sessions under ~/.grok/sessions/<encoded-cwd>/<session>/chat_history.jsonl, deduplicates across CWD encoding variants and hook-observed GROK_HOME roots, and extracts title/model/branch metadata with an improved early-exit strategy (no longer gated on git.branch).
  • Safe resume commands: singleQuotedShellCommand replaces ad-hoc string concatenation for built-in Grok, wrapping each env assignment and argv token in single quotes with proper '\'' escaping; the -r <id> flag is now plumbed through the surface resume path in the CLI.
  • Shell integration and wrapper: The bundled Resources/bin/grok wrapper discovers the real binary (including alternate names), exports launch metadata, and conditionally installs hooks; bash/zsh integration is refactored into a shared _cmux_install_cli_wrapper helper that installs both claude and grok wrappers.

Confidence Score: 5/5

Safe to merge; the previously-flagged CWD-filter discard is fixed and regression-covered, the resume command quoting is sound, and no data-loss or security paths were found.

All three bugs surfaced in earlier review rounds are addressed: alternate binary name detection, early-exit branch gate, and the CWD filter being silently discarded. The new single-quoted shell command builder handles special characters correctly throughout, and the shell integration changes are scoped to hardcoded names. Remaining findings are style-level: dead switch arms and a redundant needle sub-array in the transcript pre-filter.

Sources/SessionIndexView.swift — the dead case .grok arms in shouldParseRawLine and inferredRole, and the grokRoleNeedles composition, are worth tidying before this pattern spreads further.

Important Files Changed

Filename Overview
Sources/SessionIndexRegisteredAgents.swift Adds GrokSessionLocator and loadGrokEntries for native Grok Vault indexing; introduces singleQuotedShellCommand formatting and CWD-encoded session root discovery with deduplication.
Sources/SessionIndexView.swift Extends transcript preview parsing with Grok layout mode; adds grokRoleNeedles, inferredGrokRole, and usesGrokTranscriptLayout routing. The .grok switch arms in shouldParseRawLine and inferredRole are dead code because usesGrokTranscriptLayout is always true for that agent.
Sources/SessionIndexStore.swift Wires cwdFilter correctly into the .grok branch of searchSessions; previously-flagged bug (scopedCwd computed but overwritten to nil) is fixed and covered by testGrokAgentSearchScopeUsesCurrentDirectoryCWDFilter.
Sources/VaultAgentRegistry.swift Adds builtInGrok registration and processNames multi-name detection; decoding handles both singular and list forms cleanly.
Sources/VaultAgentProcessScanner.swift Adds grokResumeSessionID argv parser and grokSessionDirectory case to session ID source resolution; handles -r/--resume in both space-separated and = forms.
Resources/bin/grok Bundled wrapper that discovers the real grok binary, installs cmux hooks for chat-like invocations, and exports launch metadata; should_install_grok_hooks heuristic covers resume, passthrough-only, and built-in subcommand patterns.
Sources/SessionIndexModels.swift Replaces ad-hoc grok resume command assembly with singleQuotedShellCommand that builds env/argv token lists and applies shellSingleQuote to each; handles GROK_HOME environment correctly.
CLI/cmux.swift Adds grok surface resume via agentSurfaceResumeWithOption with -r flag; updates grokSessionURL to search multiple encoded-CWD roots; adds createConfigDirIfMissing hook logic.
cmuxTests/PiVaultAgentPersistenceTests.swift Adds comprehensive Grok Vault persistence tests covering native chat history loading, title extraction, branch discovery, observed-home lookup, custom state dir, registered agent routing, and CWD filter scope.
cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift Adds regression test for the Grok hook resume binding publication path including GROK_HOME, model, permission-mode, and the new single-quoted command format.

Sequence Diagram

sequenceDiagram
    participant Shell as User Shell
    participant Wrapper as Resources/bin/grok
    participant RealGrok as Real grok binary
    participant CLI as cmux CLI
    participant Store as SessionIndexStore
    participant Locator as GrokSessionLocator

    Shell->>Wrapper: grok [args]
    Wrapper->>Wrapper: find_real_grok() — searches PATH for grok / grok-macos-aarch64 / grok-macos-aarch
    Wrapper->>Wrapper: should_install_grok_hooks() — skip for passthrough flags / subcommands
    Wrapper->>CLI: hooks grok install --yes (via CMUX_SOCKET_PATH)
    Wrapper->>Wrapper: export CMUX_AGENT_LAUNCH_KIND / EXECUTABLE / ARGV_B64 / CWD
    Wrapper->>RealGrok: exec real grok [args]

    Note over Store,Locator: Vault search (agent .grok scope)
    Store->>Locator: sessionRoots(registration, cwdFilter, env, observedGrokHomes)
    Locator->>Locator: encodedSessionCWDs(cwd) — raw + standardizedPath variants
    Locator-->>Store: [GrokSessionRoot] (sessionsRoot, grokHomeForResume)
    Store->>Store: enumerateGrokHistoryCandidates / ripgrepMatchingPaths
    Store->>Store: extractGrokSessionMetadata — title, model, branch
    Store-->>Store: SessionEntry with AgentSpecifics.grok(model, permMode, sandbox, grokHome)
    Store->>Store: "singleQuotedShellCommand — 'env' 'GROK_HOME=...' 'grok' '-r' 'session-id'"
Loading

Reviews (8): Last reviewed commit: "Fix Grok agent-scoped Vault filtering" | Re-trigger Greptile

Comment thread Resources/bin/grok
Comment thread Sources/SessionIndexRegisteredAgents.swift Outdated
Comment thread CLI/cmux.swift
Comment thread Sources/SessionIndexRegisteredAgents.swift

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1 issue found across 3 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread Sources/SessionIndexRegisteredAgents.swift
Comment thread Resources/shell-integration/cmux-bash-integration.bash
Comment thread Resources/shell-integration/cmux-zsh-integration.zsh
@cubic-dev-ai

cubic-dev-ai Bot commented May 20, 2026

Copy link
Copy Markdown

You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment @cubic-dev-ai review.

Comment thread Sources/SessionIndexRegisteredAgents.swift Outdated

Copy link
Copy Markdown
Contributor

Dogfood update from the tagged dev build:

  • Built and opened cmux DEV issue-4394-grok-vault-resume.app from branch issue-4394-grok-vault-resume.
  • Confirmed Grok Vault rows now render with AgentIcons/Grok instead of the generic fallback icon.
  • Confirmed Grok Vault titles now show the user prompt from <user_query> (for example 1+1 / 2+2) instead of injected <user_info> metadata.
  • Confirmed the remaining BUILD COMMAND... rows shown in the Vault are Codex sessions, not Grok sessions.

CI: required checks are green at commit 843734760; continuing to watch the remaining non-required CI/CD checks.

Copy link
Copy Markdown
Contributor

Follow-up for Cursor Bugbot's custom hook state finding:

  • Fixed observedGrokHomes to read the Grok hook store via RestorableAgentKind.grok.hookStoreFileURL(...), matching hook persistence and honoring CMUX_AGENT_HOOK_STATE_DIR.
  • Added testGrokVaultLoadsHookObservedShellGrokHomeFromCustomStateDir to cover a hook-observed GROK_HOME stored outside the default ~/.cmuxterm directory.

Pushed as f95b25b99; continuing to watch CI/CD.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

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.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit f95b25b. Configure here.

Comment thread Sources/SessionIndexRegisteredAgents.swift
Comment thread Sources/SessionIndexStore.swift Outdated

Copy link
Copy Markdown
Contributor

Follow-up for the latest review findings:

  • Fixed Grok agent-scoped Vault search to pass the current working directory through as cwdFilter, so the Grok agent tab respects the active folder scope instead of showing all Grok sessions.
  • Kept Grok metadata scanning fast while allowing branch discovery shortly after stable metadata is found, so git.branch is not dropped when it appears on a later JSONL line.
  • Added behavior coverage for both cases.

Pushed as 12ae177f1; CI/CD is restarting and I am continuing to monitor it.

@lawrencecchen
lawrencecchen dismissed stale reviews from coderabbitai[bot], coderabbitai[bot], coderabbitai[bot], and coderabbitai[bot] May 20, 2026 09:10

Stale automated CodeRabbit review on an old commit. The inline feedback from this review has been addressed or superseded by later commits, review threads are resolved, and the latest CodeRabbit status is passing on head 12ae177.

@austinywang
austinywang merged commit 4bf6c52 into main May 20, 2026
18 checks passed

Copy link
Copy Markdown
Contributor

Reviewer-blocker follow-up:

  • Dismissed four stale automated CodeRabbit CHANGES_REQUESTED reviews from old commits after their inline feedback was addressed/superseded and all related threads were resolved.
  • Current head remains 12ae177f19caf91389770488c8aa2d0c2a3717c1.
  • GitHub merge state is now CLEAN; CI, CodeRabbit, Cursor Bugbot, Greptile, Socket, and Vercel checks are green.

No code changes in this pass.

This branch was successfully deployed

1 active deployment
Preview – cmux — 12ae177f Deployed May 20, 2026 by vercel[bot]
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.

Native Vault integration and reliable resume for Grok (cmux hooks)

2 participants