Skip to content

feat(cli): manage client-owned sidebar groups - #5822

Open
Kitenite wants to merge 3 commits into
mainfrom
agent/cli-sidebar-sections
Open

Kitenite wants to merge 3 commits into
mainfrom
agent/cli-sidebar-sections

Conversation

@Kitenite

@Kitenite Kitenite commented Jul 21, 2026 •

Copy link
Copy Markdown
Member

Summary

  • add superset sidebar list, group create/rename/delete/collapse/expand, and workspace move/ungroup commands
  • persist sidebar layout as client-owned state scoped by organization and user, independent of resource hosts
  • synchronize the same versioned state between the bundled CLI and Electron through atomic file writes, file watching, and revision checks
  • migrate existing renderer local state safely, including the CLI-first / Electron-closed case
  • keep pane layouts and other workspace-local fields outside the sidebar state document
  • document the client/host ownership boundary and the real bun dev CLI-to-CDP workflow

Architecture

A host can serve multiple clients, so it does not own their presentation preferences. State lives at:

<SUPERSET_HOME_DIR>/client-state/<organizationId>/<userId>/sidebar.json

The CLI reads and writes this client store directly. Electron main exposes the same store to its renderer over IPC and watches atomic renames. Host services remain responsible only for project/workspace resource lookup; this PR has no sidebar event-bus, acknowledgement, or host tRPC bridge.

Writes are serialized with a short-lived file lock. Renderer replacements use revision compare-and-swap so a stale window cannot overwrite a newer CLI mutation. Existing localStorage is merged once; CLI-first writes remain pending migration until Electron opens.

UX and compatibility

Names resolve by exact case-insensitive match while stable IDs remain available for automation. Ambiguous names fail with candidate IDs. Deleting a group ungroups its workspaces and never deletes them. Commands work while the Electron renderer is closed; resource-name lookup still requires the local host service.

The first Electron launch migrates existing sidebar rows. The persisted format is versioned, and organization/user scoping prevents two clients on one host from accidentally sharing layout.

Validation

  • bun run lint
  • bun run typecheck — 36/36 package tasks
  • 16 focused reducer, file-store, migration, concurrency, name-resolution, renderer synchronization, and pane-preservation tests
  • bun run test:cli-e2e — 8/8 assertions, 9 commands
  • real root bun dev bundled CLI against Electron CDP on final commit 83ec66e6e
    • healthy host status
    • create group and move workspace
    • visible expanded/collapsed group state
    • close renderer, rename through CLI with no CDP page target, reopen, and restore group/workspace
    • verified versioned client-state file and zero leftover lock/temp files
    • cleaned up only the temporary group

Local evidence: test-results/cli-cdp/cli-sidebar-final-20260721-090415/ contains machine-readable CLI/CDP assertions, persisted-state snapshot, screenshots, and a 15.5s H.264 CDP screencast.

Summary by CodeRabbit

  • New Features

    • Added sidebar workspace groups for organizing workspaces within projects.
    • Groups can be created, renamed, collapsed, expanded, moved, and deleted.
    • Added CLI commands to list sidebar state and manage groups and workspace placement.
    • Sidebar layout now persists across desktop and CLI sessions, including after restarts.
  • Bug Fixes

    • Deleting a group preserves its workspaces by returning them to the ungrouped project area.
    • Improved handling of ambiguous project, workspace, and group names.
  • Documentation

    • Added CLI reference and end-to-end guidance for sidebar group management.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a shared organization/user-scoped sidebar state package with filesystem persistence, Electron synchronization, renderer group mutations, CLI sidebar commands, tests, documentation, and CDP acceptance coverage.

Changes

Sidebar state foundation

Layer / File(s) Summary
Client-state schema and persistence
packages/client-state/*
Defines sidebar state and command schemas, implements deterministic group/workspace mutations, and persists versioned state with locking, atomic writes, migration, watchers, and revision conflict checks.
Desktop state bridge and synchronization
apps/desktop/src/lib/trpc/routers/*, apps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/*, apps/desktop/src/renderer/routes/_authenticated/layout.tsx
Adds tRPC read, initialize, replace, and subscription procedures; synchronizes persisted snapshots with renderer collections; and mounts the controller in the authenticated layout.
Renderer group mutation implementation
apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/*
Centralizes sidebar ordering, workspace materialization, group lifecycle operations, and hook delegation, with mutation coverage for grouping, deletion, ordering, and project validation.
CLI sidebar commands and resolution
packages/cli/src/commands/sidebar/*
Adds scoped client-state execution, ID/name resolution, list and move commands, and create, delete, rename, collapse, and expand group commands.
Sidebar validation and documentation
apps/desktop/docs/CLI_CDP_E2E.md, apps/docs/content/docs/cli/cli-reference.mdx, packages/cli/CLI_SPEC_CURRENT.md, packages/cli/TODO.md
Documents sidebar commands, state ownership and persistence, bundled CLI acceptance flows, restart validation, and implementation status.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant ClientStateStore
  participant ElectronTRPC
  participant SidebarStateController
  participant SidebarCollections
  CLI->>ClientStateStore: execute scoped sidebar command
  ClientStateStore-->>CLI: updated sidebar state
  SidebarStateController->>ElectronTRPC: get or initialize state
  ElectronTRPC->>ClientStateStore: read sidebar.json
  ClientStateStore-->>ElectronTRPC: persisted document
  ElectronTRPC-->>SidebarStateController: sidebar document
  SidebarStateController->>SidebarCollections: apply snapshot
  SidebarStateController->>ElectronTRPC: replace local snapshot
  ElectronTRPC->>ClientStateStore: persist with expected revision
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise, conventional, and captures the main CLI sidebar-group management change.
Description check ✅ Passed The description covers the required what/why, testing, architecture, and validation details, with only the checklist left incomplete.
✨ 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 agent/cli-sidebar-sections

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.

@greptile-apps

greptile-apps Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds CLI management for desktop sidebar groups. The main changes are:

  • New commands for listing, creating, renaming, deleting, collapsing, and expanding groups.
  • Workspace move and ungroup commands with exact name or ID resolution.
  • A host-to-renderer command and acknowledgement bridge.
  • Shared sidebar mutation helpers for UI and CLI operations.
  • Documentation and focused protocol and mutation tests.

Confidence Score: 4/5

The acknowledgement path can report both false success and false failure, so these issues need to be fixed before merging.

  • Results are accepted from a connection that was not verified as the command target.
  • A reconnect can discard the result after the renderer has already changed sidebar state.
  • The shared mutation and CLI resolution code otherwise preserve the main sidebar invariants.

packages/host-service/src/events/event-bus.ts and packages/workspace-client/src/lib/eventBus.ts

Security Review

Sidebar acknowledgements are not tied to the targeted renderer connection. Any connected client that receives the broadcast command ID can return the accepted result first, allowing false success without the requested mutation being applied.

Important Files Changed

Filename Overview
packages/host-service/src/events/event-bus.ts Adds pending sidebar commands and timeout-based acknowledgements, but accepts results without binding them to the targeted client.
packages/workspace-client/src/lib/eventBus.ts Adds sidebar command delivery and result sending, but drops results when the socket is reconnecting.
apps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/SidebarCommandController.tsx Executes machine-targeted commands through the shared mutation layer and returns the resulting snapshot.
apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts Extracts canonical group and workspace placement mutations for reuse by the UI and CLI.
packages/host-service/src/trpc/router/sidebar/sidebar.ts Adds validated local sidebar procedures and forwards commands to the renderer bridge.
packages/cli/src/commands/sidebar/shared.ts Adds local host execution and exact case-insensitive ID or name resolution with ambiguity errors.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant CLI
    participant Host as Host service
    participant Target as Target renderer
    participant Other as Other client
    CLI->>Host: sidebar.execute(command)
    Host-->>Target: sidebar:command(commandId, targetMachineId)
    Host-->>Other: sidebar:command(commandId, targetMachineId)
    alt Another client responds first
        Other->>Host: sidebar:result(commandId, state)
        Host-->>CLI: Success with unrelated state
    else Target applies command
        Target->>Target: Mutate sidebar collections
        alt Socket remains open
            Target->>Host: sidebar:result(commandId, state)
            Host-->>CLI: Success
        else Socket reconnects
            Note over Target,Host: Result is dropped
            Host-->>CLI: Timeout after mutation
        end
    end
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant CLI
    participant Host as Host service
    participant Target as Target renderer
    participant Other as Other client
    CLI->>Host: sidebar.execute(command)
    Host-->>Target: sidebar:command(commandId, targetMachineId)
    Host-->>Other: sidebar:command(commandId, targetMachineId)
    alt Another client responds first
        Other->>Host: sidebar:result(commandId, state)
        Host-->>CLI: Success with unrelated state
    else Target applies command
        Target->>Target: Mutate sidebar collections
        alt Socket remains open
            Target->>Host: sidebar:result(commandId, state)
            Host-->>CLI: Success
        else Socket reconnects
            Note over Target,Host: Result is dropped
            Host-->>CLI: Timeout after mutation
        end
    end
Loading
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
packages/host-service/src/events/event-bus.ts:164-166
**Acknowledgement Is Not Bound To Target**

A sidebar result is accepted using only its broadcast `commandId`; the sending socket is not checked against `targetMachineId`. Another connected client can acknowledge first without applying the command, causing the CLI to report success with an unrelated sidebar snapshot.

### Issue 2 of 2
packages/workspace-client/src/lib/eventBus.ts:357-359
**Reconnect Drops Successful Acknowledgement**

If the socket disconnects after the renderer applies a command but before this send, `sendCommand` silently drops the result and does not replay it after reconnection. The host then reports a timeout even though state changed, so retrying create or delete can conflict with the mutation that already succeeded.

Reviews (1): Last reviewed commit: "feat(cli): manage desktop sidebar groups" | Re-trigger Greptile

Comment on lines +164 to +166
} else if (message.type === "sidebar:result") {
this.resolveSidebarCommand(message);
}

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.

P1 security Acknowledgement Is Not Bound To Target

A sidebar result is accepted using only its broadcast commandId; the sending socket is not checked against targetMachineId. Another connected client can acknowledge first without applying the command, causing the CLI to report success with an unrelated sidebar snapshot.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/host-service/src/events/event-bus.ts
Line: 164-166

Comment:
**Acknowledgement Is Not Bound To Target**

A sidebar result is accepted using only its broadcast `commandId`; the sending socket is not checked against `targetMachineId`. Another connected client can acknowledge first without applying the command, causing the CLI to report success with an unrelated sidebar snapshot.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 357 to 359
}
},

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.

P1 Reconnect Drops Successful Acknowledgement

If the socket disconnects after the renderer applies a command but before this send, sendCommand silently drops the result and does not replay it after reconnection. The host then reports a timeout even though state changed, so retrying create or delete can conflict with the mutation that already succeeded.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/workspace-client/src/lib/eventBus.ts
Line: 357-359

Comment:
**Reconnect Drops Successful Acknowledgement**

If the socket disconnects after the renderer applies a command but before this send, `sendCommand` silently drops the result and does not replay it after reconnection. The host then reports a timeout even though state changed, so retrying create or delete can conflict with the mutation that already succeeded.

How can I resolve this? If you propose a fix, please make it concise.

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Preview Deployment

🔗 Preview Links

Service Status Link
Neon Database (Neon) ✅ View Branch
Vercel API (Vercel) ✅ Open Preview
Vercel Web (Vercel) ✅ Open Preview
Vercel Marketing (Vercel) ✅ Open Preview
Vercel Admin (Vercel) ✅ Open Preview
Vercel Docs (Vercel) ✅ Open Preview

Preview updates automatically with new commits

@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)
apps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/SidebarCommandController.tsx (1)

23-65: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add an exhaustiveness guard to the command switch.

All current SidebarCommand variants are handled, but there's no default branch asserting never. If a new action is added to the union later, TypeScript won't flag a missing case here — it will silently fall through to returning the snapshot without performing the intended mutation.

♻️ Proposed fix
 			case "set-group-collapsed":
 				setSidebarGroupCollapsed(
 					collections,
 					command.groupId,
 					command.collapsed,
 				);
 				break;
+			default: {
+				const exhaustiveCheck: never = command;
+				throw new Error(
+					`Unhandled sidebar command: ${JSON.stringify(exhaustiveCheck)}`,
+				);
+			}
 		}
🤖 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/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/SidebarCommandController.tsx`
around lines 23 - 65, Update the action switch in executeCommand to add a
default exhaustiveness guard that accepts the command action as never and fails
for any unhandled SidebarCommand variant. Keep the existing cases and snapshot
return unchanged.
apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts (1)

1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider promoting this module to the shared parent of its two consumers.

sidebarGroupMutations.ts is imported by both useDashboardSidebarState.ts (same folder) and SidebarCommandController.tsx (a sibling components/ tree), so per the co-location guideline it should live at the highest shared parent (_authenticated/) rather than nested under hooks/useDashboardSidebarState/.

As per path instructions: "Co-locate components, hooks, utilities, constants, configuration, tests, and stories with their usage; nest single-use items under the parent and promote items used two or more times to the highest shared parent."

🤖 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/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts`
around lines 1 - 9, Move the sidebarGroupMutations module to the highest shared
_authenticated parent used by useDashboardSidebarState.ts and
SidebarCommandController.tsx, then update both consumers’ imports to the new
location. Preserve the module’s exports and behavior without changing unrelated
sidebar logic.

Source: Path instructions

🤖 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
`@apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts`:
- Around line 151-183: Update createSidebarGroup to normalize input.name with
trim before the existing-group idempotency comparison and use that same
normalized value when inserting the new section. Preserve returning
existing.sectionId for matching project and normalized name, while still
rejecting genuinely conflicting groups.

In `@packages/cli/src/commands/sidebar/move/command.ts`:
- Around line 18-23: Update the destination validation in the move command to
coerce options.ungrouped to a strict boolean before comparing it with
options.group !== undefined. Preserve the existing exactly-one-destination rule
so omitting both flags triggers the CLIError.

---

Nitpick comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/SidebarCommandController.tsx`:
- Around line 23-65: Update the action switch in executeCommand to add a default
exhaustiveness guard that accepts the command action as never and fails for any
unhandled SidebarCommand variant. Keep the existing cases and snapshot return
unchanged.

In
`@apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts`:
- Around line 1-9: Move the sidebarGroupMutations module to the highest shared
_authenticated parent used by useDashboardSidebarState.ts and
SidebarCommandController.tsx, then update both consumers’ imports to the new
location. Preserve the module’s exports and behavior without changing unrelated
sidebar logic.
🪄 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: 923320fe-835d-443d-bb2c-f876421395d8

📥 Commits

Reviewing files that changed from the base of the PR and between 5f1a322 and 8d3217b.

📒 Files selected for processing (31)
  • apps/desktop/docs/CLI_CDP_E2E.md
  • apps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/SidebarCommandController.tsx
  • apps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.test.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/useDashboardSidebarState.ts
  • apps/desktop/src/renderer/routes/_authenticated/layout.tsx
  • apps/docs/content/docs/cli/cli-reference.mdx
  • packages/cli/CLI_SPEC_CURRENT.md
  • packages/cli/TODO.md
  • packages/cli/src/commands/sidebar/groups/collapse/command.ts
  • packages/cli/src/commands/sidebar/groups/create/command.ts
  • packages/cli/src/commands/sidebar/groups/delete/command.ts
  • packages/cli/src/commands/sidebar/groups/expand/command.ts
  • packages/cli/src/commands/sidebar/groups/meta.ts
  • packages/cli/src/commands/sidebar/groups/rename/command.ts
  • packages/cli/src/commands/sidebar/groups/set-collapsed.ts
  • packages/cli/src/commands/sidebar/list/command.ts
  • packages/cli/src/commands/sidebar/meta.ts
  • packages/cli/src/commands/sidebar/move/command.ts
  • packages/cli/src/commands/sidebar/shared.test.ts
  • packages/cli/src/commands/sidebar/shared.ts
  • packages/host-service/src/events/event-bus.test.ts
  • packages/host-service/src/events/event-bus.ts
  • packages/host-service/src/events/index.ts
  • packages/host-service/src/events/types.ts
  • packages/host-service/src/trpc/router/router.ts
  • packages/host-service/src/trpc/router/sidebar/index.ts
  • packages/host-service/src/trpc/router/sidebar/sidebar.ts
  • packages/workspace-client/src/lib/eventBus.test.ts
  • packages/workspace-client/src/lib/eventBus.ts

@Kitenite Kitenite changed the title feat(cli): manage desktop sidebar groups feat(cli): manage client-owned sidebar groups Jul 21, 2026

@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: 3

🧹 Nitpick comments (2)
packages/client-state/src/schema.ts (1)

16-23: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

sidebarGroupSchema.name allows empty strings, unlike the command schema.

sidebarCommandSchema's create-group/rename-group actions enforce z.string().trim().min(1) for name, but the persisted snapshot's sidebarGroupSchema.name has no such constraint. Data merged in from legacy renderer state (via mergeRendererMigration in store.ts) bypasses the stricter command-level validation, so an empty group name could be silently persisted and read back.

Proposed tightening
 export const sidebarGroupSchema = z.object({
 	id: z.string().min(1),
 	projectId: z.string().min(1),
-	name: z.string(),
+	name: z.string().min(1),
 	tabOrder: z.number().finite(),
 	isCollapsed: z.boolean(),
 	color: z.string().nullable(),
 });
🤖 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 `@packages/client-state/src/schema.ts` around lines 16 - 23, Update
sidebarGroupSchema.name to require a trimmed, non-empty string, matching the
name validation used by sidebarCommandSchema create-group and rename-group
actions. Preserve the existing schema shape while preventing empty or
whitespace-only group names from being persisted through mergeRendererMigration.
packages/client-state/src/store.ts (1)

141-169: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Revision bumps even for no-op/idempotent commands.

updateSidebarState always writes a new document with revision: current.document.revision + 1 (Lines 156-164), even when command was a no-op (e.g., sidebar.ts's idempotent create-group re-application returns logically-unchanged state). This means replaying an idempotent command still advances the revision and rewrites sidebar.json, which can cause spurious conflict: true results in replaceSidebarState for clients holding a stale expectedRevision based on the pre-replay state, even though the sidebar content they observed hasn't actually changed.

Consider comparing the new state (e.g. via JSON.stringify or a structural diff) against current.document.state and skipping the write/revision bump when unchanged.

Also applies to: 209-218

🤖 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 `@packages/client-state/src/store.ts` around lines 141 - 169, Update
updateSidebarState to detect when next.state is logically unchanged from
current.document.state before constructing and writing a new document; for no-op
updates, return current without incrementing revision or rewriting the file.
Preserve metadata-only changes such as rendererMigrated when they differ, and
continue writing changed state normally.
🤖 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
`@apps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/SidebarStateController.tsx`:
- Around line 37-96: Add strict readiness tracking for all three useLiveQuery
calls and derive a combined collectionsReady value. In the initialization
effect, continue accepting a rendererMigrated result immediately, but defer the
sidebarState.initialize call and getSidebarStateSnapshot(collections) until
collectionsReady is true; include that readiness value in the effect
dependencies so initialization retries when hydration completes.
- Around line 98-124: Update SidebarStateController’s sidebarState.replace
failure handling to fetch the current server snapshot via sidebarState.get, then
pass that document through acceptDocument so revisionRef and UI state are
reconciled before future local edits retry. Also change the onChanged
subscription handler to reconcile incoming snapshots with pending local changes
instead of unconditionally applying them, preserving local records during the
debounce window and ensuring they are merged or retried for persistence.

In `@packages/client-state/src/store.ts`:
- Around line 230-238: Update the watcher callback around watch and
readSidebarState so missing filename values are treated as potential
sidebar.json changes rather than returned early. Keep filtering known
non-sidebar filenames, while allowing null or undefined filenames to proceed
through the existing debounced re-read and onChange flow.

---

Nitpick comments:
In `@packages/client-state/src/schema.ts`:
- Around line 16-23: Update sidebarGroupSchema.name to require a trimmed,
non-empty string, matching the name validation used by sidebarCommandSchema
create-group and rename-group actions. Preserve the existing schema shape while
preventing empty or whitespace-only group names from being persisted through
mergeRendererMigration.

In `@packages/client-state/src/store.ts`:
- Around line 141-169: Update updateSidebarState to detect when next.state is
logically unchanged from current.document.state before constructing and writing
a new document; for no-op updates, return current without incrementing revision
or rewriting the file. Preserve metadata-only changes such as rendererMigrated
when they differ, and continue writing changed state normally.
🪄 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: 95f8c1ed-9f36-4ae8-be6b-1ad5f2de2589

📥 Commits

Reviewing files that changed from the base of the PR and between 8d3217b and 83ec66e.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (29)
  • apps/desktop/docs/CLI_CDP_E2E.md
  • apps/desktop/package.json
  • apps/desktop/src/lib/trpc/routers/index.ts
  • apps/desktop/src/lib/trpc/routers/sidebar-state/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/SidebarStateController.tsx
  • apps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/applySidebarStateSnapshot.test.ts
  • apps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/applySidebarStateSnapshot.ts
  • apps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.test.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.ts
  • apps/desktop/src/renderer/routes/_authenticated/layout.tsx
  • apps/docs/content/docs/cli/cli-reference.mdx
  • packages/cli/CLI_SPEC_CURRENT.md
  • packages/cli/TODO.md
  • packages/cli/package.json
  • packages/cli/src/commands/sidebar/groups/create/command.ts
  • packages/cli/src/commands/sidebar/list/command.ts
  • packages/cli/src/commands/sidebar/move/command.ts
  • packages/cli/src/commands/sidebar/shared.test.ts
  • packages/cli/src/commands/sidebar/shared.ts
  • packages/client-state/README.md
  • packages/client-state/package.json
  • packages/client-state/src/index.ts
  • packages/client-state/src/schema.ts
  • packages/client-state/src/sidebar.test.ts
  • packages/client-state/src/sidebar.ts
  • packages/client-state/src/store.test.ts
  • packages/client-state/src/store.ts
  • packages/client-state/tsconfig.json
🚧 Files skipped from review as they are similar to previous changes (7)
  • packages/cli/src/commands/sidebar/shared.test.ts
  • packages/cli/src/commands/sidebar/groups/create/command.ts
  • packages/cli/src/commands/sidebar/move/command.ts
  • packages/cli/src/commands/sidebar/list/command.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.test.ts
  • packages/cli/CLI_SPEC_CURRENT.md
  • apps/docs/content/docs/cli/cli-reference.mdx

Comment on lines +37 to +96
const { data: projectRows = [] } = useLiveQuery(
(query) => query.from({ projects: collections.v2SidebarProjects }),
[collections],
);
const { data: groupRows = [] } = useLiveQuery(
(query) => query.from({ groups: collections.v2SidebarSections }),
[collections],
);
const { data: workspaceRows = [] } = useLiveQuery(
(query) =>
query
.from({ workspaces: collections.v2WorkspaceLocalState })
.select(({ workspaces }) => ({
workspaceId: workspaces.workspaceId,
sidebarState: workspaces.sidebarState,
})),
[collections],
);
const localCollectionRevision = useMemo(
() => JSON.stringify([projectRows, groupRows, workspaceRows]),
[groupRows, projectRows, workspaceRows],
);

const acceptDocument = useCallback(
(document: SidebarStateDocument) => {
persistedSignatureRef.current = stateSignature(document);
revisionRef.current = document.revision;
applySidebarStateSnapshot(collections, document.state);
readyRef.current = true;
},
[collections],
);

useEffect(() => {
let cancelled = false;
readyRef.current = false;
void electronTrpcClient.sidebarState.get
.query(scope)
.then(async (result) => {
if (cancelled) return;
if (result.document.rendererMigrated) {
acceptDocument(result.document);
return;
}
const initialized =
await electronTrpcClient.sidebarState.initialize.mutate({
scope,
state: getSidebarStateSnapshot(collections),
});
if (!cancelled) acceptDocument(initialized.document);
})
.catch((error) => {
if (!cancelled) {
console.error("[sidebar-state] Failed to initialize", error);
}
});
return () => {
cancelled = true;
};
}, [acceptDocument, collections, scope]);

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Gate the initial snapshot write on live-query readiness.

None of the three useLiveQuery calls check readiness, yet the init effect (lines 73-92) unconditionally uses getSidebarStateSnapshot(collections) to seed sidebarState.initialize when the persisted doc isn't yet renderer-migrated. If the collections haven't finished hydrating from local storage/sync at that point, this writes an incomplete/empty snapshot as the one-time canonical initial state — a non-idempotent write that can permanently drop existing sidebar groups/workspaces on first migration.

🛡️ Proposed fix: gate on readiness before writing the initial snapshot
 	const { data: projectRows = [] } = useLiveQuery(
+	const { data: projectRows = [], isReady: projectsReady } = useLiveQuery(
 		(query) => query.from({ projects: collections.v2SidebarProjects }),
 		[collections],
 	);
-	const { data: groupRows = [] } = useLiveQuery(
+	const { data: groupRows = [], isReady: groupsReady } = useLiveQuery(
 		(query) => query.from({ groups: collections.v2SidebarSections }),
 		[collections],
 	);
-	const { data: workspaceRows = [] } = useLiveQuery(
+	const { data: workspaceRows = [], isReady: workspacesReady } = useLiveQuery(
 		(query) =>
 			query
 				.from({ workspaces: collections.v2WorkspaceLocalState })
 				.select(({ workspaces }) => ({
 					workspaceId: workspaces.workspaceId,
 					sidebarState: workspaces.sidebarState,
 				})),
 		[collections],
 	);
+	const collectionsReady = projectsReady && groupsReady && workspacesReady;

Then guard the initialize branch of the init effect on collectionsReady (re-running once it flips true), while still applying get's rendererMigrated result immediately regardless of readiness.

As per coding guidelines: "wait for strict readiness before deriving missing rows or writing defaults unless writes are provably idempotent."

🤖 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/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/SidebarStateController.tsx`
around lines 37 - 96, Add strict readiness tracking for all three useLiveQuery
calls and derive a combined collectionsReady value. In the initialization
effect, continue accepting a rendererMigrated result immediately, but defer the
sidebarState.initialize call and getSidebarStateSnapshot(collections) until
collectionsReady is true; include that readiness value in the effect
dependencies so initialization retries when hydration completes.

Source: Coding guidelines

Comment on lines +98 to +124
electronTrpc.sidebarState.onChanged.useSubscription(scope, {
onData: (result) => acceptDocument(result.document),
});

useEffect(() => {
if (!readyRef.current || !localCollectionRevision) return;
const state = getSidebarStateSnapshot(collections);
const signature = JSON.stringify(state);
if (signature === persistedSignatureRef.current) return;

const timer = window.setTimeout(() => {
void electronTrpcClient.sidebarState.replace
.mutate({
scope,
state,
expectedRevision: revisionRef.current,
})
.then((result) => acceptDocument(result.document))
.catch((error) => {
console.error(
"[sidebar-state] Failed to persist local changes",
error,
);
});
}, 50);
return () => window.clearTimeout(timer);
}, [acceptDocument, collections, localCollectionRevision, scope]);

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Reconcile with server state instead of silently dropping failed/overwritten local edits.

Two related gaps here:

  • On replace failure (line 116-121), only console.error runs — no resync via sidebarState.get. The stale revisionRef is retried unchanged on the next local edit, so a conflicted write can keep failing while the UI still shows the un-persisted local change.
  • The onChanged handler (line 98-100) applies incoming snapshots unconditionally via acceptDocument/applySidebarStateSnapshot, which deletes any local record absent from the incoming snapshot. If a remote update (e.g., from the CLI or another window) arrives during the 50ms debounce window before a fresh local edit is persisted, that local edit is silently destroyed rather than merged or retried.
🛡️ Proposed fix: resync on replace failure
 			void electronTrpcClient.sidebarState.replace
 				.mutate({
 					scope,
 					state,
 					expectedRevision: revisionRef.current,
 				})
 				.then((result) => acceptDocument(result.document))
-				.catch((error) => {
+				.catch(async (error) => {
 					console.error(
 						"[sidebar-state] Failed to persist local changes",
 						error,
 					);
+					// Re-sync with the canonical state so the UI doesn't remain
+					// diverged from persisted data after a revision conflict.
+					try {
+						const latest = await electronTrpcClient.sidebarState.get.query(scope);
+						acceptDocument(latest.document);
+					} catch (syncError) {
+						console.error("[sidebar-state] Failed to resync", syncError);
+					}
 				});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
electronTrpc.sidebarState.onChanged.useSubscription(scope, {
onData: (result) => acceptDocument(result.document),
});
useEffect(() => {
if (!readyRef.current || !localCollectionRevision) return;
const state = getSidebarStateSnapshot(collections);
const signature = JSON.stringify(state);
if (signature === persistedSignatureRef.current) return;
const timer = window.setTimeout(() => {
void electronTrpcClient.sidebarState.replace
.mutate({
scope,
state,
expectedRevision: revisionRef.current,
})
.then((result) => acceptDocument(result.document))
.catch((error) => {
console.error(
"[sidebar-state] Failed to persist local changes",
error,
);
});
}, 50);
return () => window.clearTimeout(timer);
}, [acceptDocument, collections, localCollectionRevision, scope]);
electronTrpc.sidebarState.onChanged.useSubscription(scope, {
onData: (result) => acceptDocument(result.document),
});
useEffect(() => {
if (!readyRef.current || !localCollectionRevision) return;
const state = getSidebarStateSnapshot(collections);
const signature = JSON.stringify(state);
if (signature === persistedSignatureRef.current) return;
const timer = window.setTimeout(() => {
void electronTrpcClient.sidebarState.replace
.mutate({
scope,
state,
expectedRevision: revisionRef.current,
})
.then((result) => acceptDocument(result.document))
.catch(async (error) => {
console.error(
"[sidebar-state] Failed to persist local changes",
error,
);
// Re-sync with the canonical state so the UI doesn't remain
// diverged from persisted data after a revision conflict.
try {
const latest = await electronTrpcClient.sidebarState.get.query(scope);
acceptDocument(latest.document);
} catch (syncError) {
console.error("[sidebar-state] Failed to resync", syncError);
}
});
}, 50);
return () => window.clearTimeout(timer);
}, [acceptDocument, collections, localCollectionRevision, scope]);
🤖 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/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/SidebarStateController.tsx`
around lines 98 - 124, Update SidebarStateController’s sidebarState.replace
failure handling to fetch the current server snapshot via sidebarState.get, then
pass that document through acceptDocument so revisionRef and UI state are
reconciled before future local edits retry. Also change the onChanged
subscription handler to reconcile incoming snapshots with pending local changes
instead of unconditionally applying them, preserving local records during the
debounce window and ensuring they are merged or retried for persistence.

Comment on lines +230 to +238
const watcher = watch(directory, (_event, filename) => {
if (filename !== "sidebar.json") return;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
void readSidebarState(homeDir, scope)
.then(onChange)
.catch(() => {});
}, 20);
});

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the file and inspect the relevant section with line numbers.
git ls-files 'packages/client-state/src/store.ts'
wc -l packages/client-state/src/store.ts
sed -n '200,270p' packages/client-state/src/store.ts

# Find watchSidebarState usages/context.
rg -n "watchSidebarState|sidebar.json|fs\.watch|watch\(" packages/client-state/src/store.ts packages -g '!**/node_modules/**'

# Inspect adjacent router/subscription code that depends on this watcher.
sed -n '1,220p' apps/desktop/src/lib/trpc/routers/sidebar-state/index.ts

Repository: superset-sh/superset

Length of output: 4835


🌐 Web query:

Node.js fs.watch filename not guaranteed provided null undefined directory watcher documentation

💡 Result:

In Node.js, the filename argument provided to the fs.watch callback is not guaranteed to be present [1][2]. Because the fs.watch API relies on native operating system file system notification facilities (such as inotify on Linux, FSEvents on macOS, or ReadDirectoryChangesW on Windows), support for reporting the specific filename varies by platform and situation [1][2]. If the operating system cannot determine or provide the name of the file that triggered the change event, Node.js will pass null as the filename argument [3][4][5]. This is a documented behavior, and developers are explicitly advised not to assume that the filename will always be provided [5][1]. Key points regarding the filename parameter: - Nullability: Always check if the filename argument is null or undefined before using it [1][2]. - Cross-Platform Variability: The availability of the filename depends on the underlying kernel and platform implementation [1][2]. Even on platforms that generally support it, specific circumstances or edge cases may result in a null value [5][1]. - Best Practice: Implement fallback logic to handle cases where the filename is null [5][1]. If your application requires robust, consistent, and cross-platform file watching, consider using a third-party library like Chokidar, which is designed to normalize these inconsistencies and provide more reliable event semantics [2]. Documentation in the Node.js project has been updated to explicitly clarify that the filename parameter can be null if the file name cannot be determined [4].

Citations:


fs.watch should not drop events when filename is missing.`

filename can be null/undefined on some platforms/filesystems, so this guard can silently skip valid sidebar.json updates and break onChanged sync. Treat a missing filename as a potential match and fall back to the debounced re-read.

🤖 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 `@packages/client-state/src/store.ts` around lines 230 - 238, Update the
watcher callback around watch and readSidebarState so missing filename values
are treated as potential sidebar.json changes rather than returned early. Keep
filtering known non-sidebar filenames, while allowing null or undefined
filenames to proceed through the existing debounced re-read and onChange flow.

This branch was previously deployed

1 inactive deployment
preview — 83ec66e6 Deployed Jul 21, 2026 by Kitenite via Deploy Admin #6729
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