Repository navigation
Conversation
📝 WalkthroughWalkthroughAdds 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. ChangesSidebar state foundation
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
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryThis PR adds CLI management for desktop sidebar groups. The main changes are:
Confidence Score: 4/5The acknowledgement path can report both false success and false failure, so these issues need to be fixed before merging.
packages/host-service/src/events/event-bus.ts and packages/workspace-client/src/lib/eventBus.ts
|
| 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
%%{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
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
| } else if (message.type === "sidebar:result") { | ||
| this.resolveSidebarCommand(message); | ||
| } |
There was a problem hiding this 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.
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.| } | ||
| }, | ||
|
|
There was a problem hiding this 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.
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.
🚀 Preview Deployment🔗 Preview Links
Preview updates automatically with new commits |
There was a problem hiding this comment.
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 winAdd an exhaustiveness guard to the command switch.
All current
SidebarCommandvariants are handled, but there's nodefaultbranch assertingnever. 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 winConsider promoting this module to the shared parent of its two consumers.
sidebarGroupMutations.tsis imported by bothuseDashboardSidebarState.ts(same folder) andSidebarCommandController.tsx(a siblingcomponents/tree), so per the co-location guideline it should live at the highest shared parent (_authenticated/) rather than nested underhooks/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
📒 Files selected for processing (31)
apps/desktop/docs/CLI_CDP_E2E.mdapps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/SidebarCommandController.tsxapps/desktop/src/renderer/routes/_authenticated/components/SidebarCommandController/index.tsapps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.test.tsapps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.tsapps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/useDashboardSidebarState.tsapps/desktop/src/renderer/routes/_authenticated/layout.tsxapps/docs/content/docs/cli/cli-reference.mdxpackages/cli/CLI_SPEC_CURRENT.mdpackages/cli/TODO.mdpackages/cli/src/commands/sidebar/groups/collapse/command.tspackages/cli/src/commands/sidebar/groups/create/command.tspackages/cli/src/commands/sidebar/groups/delete/command.tspackages/cli/src/commands/sidebar/groups/expand/command.tspackages/cli/src/commands/sidebar/groups/meta.tspackages/cli/src/commands/sidebar/groups/rename/command.tspackages/cli/src/commands/sidebar/groups/set-collapsed.tspackages/cli/src/commands/sidebar/list/command.tspackages/cli/src/commands/sidebar/meta.tspackages/cli/src/commands/sidebar/move/command.tspackages/cli/src/commands/sidebar/shared.test.tspackages/cli/src/commands/sidebar/shared.tspackages/host-service/src/events/event-bus.test.tspackages/host-service/src/events/event-bus.tspackages/host-service/src/events/index.tspackages/host-service/src/events/types.tspackages/host-service/src/trpc/router/router.tspackages/host-service/src/trpc/router/sidebar/index.tspackages/host-service/src/trpc/router/sidebar/sidebar.tspackages/workspace-client/src/lib/eventBus.test.tspackages/workspace-client/src/lib/eventBus.ts
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
packages/client-state/src/schema.ts (1)
16-23: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value
sidebarGroupSchema.nameallows empty strings, unlike the command schema.
sidebarCommandSchema'screate-group/rename-groupactions enforcez.string().trim().min(1)forname, but the persisted snapshot'ssidebarGroupSchema.namehas no such constraint. Data merged in from legacy renderer state (viamergeRendererMigrationinstore.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 winRevision bumps even for no-op/idempotent commands.
updateSidebarStatealways writes a new document withrevision: current.document.revision + 1(Lines 156-164), even whencommandwas a no-op (e.g.,sidebar.ts's idempotentcreate-groupre-application returns logically-unchanged state). This means replaying an idempotent command still advances the revision and rewritessidebar.json, which can cause spuriousconflict: trueresults inreplaceSidebarStatefor clients holding a staleexpectedRevisionbased on the pre-replay state, even though the sidebar content they observed hasn't actually changed.Consider comparing the new
state(e.g. viaJSON.stringifyor a structural diff) againstcurrent.document.stateand 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
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (29)
apps/desktop/docs/CLI_CDP_E2E.mdapps/desktop/package.jsonapps/desktop/src/lib/trpc/routers/index.tsapps/desktop/src/lib/trpc/routers/sidebar-state/index.tsapps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/SidebarStateController.tsxapps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/applySidebarStateSnapshot.test.tsapps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/applySidebarStateSnapshot.tsapps/desktop/src/renderer/routes/_authenticated/components/SidebarStateController/index.tsapps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.test.tsapps/desktop/src/renderer/routes/_authenticated/hooks/useDashboardSidebarState/sidebarGroupMutations.tsapps/desktop/src/renderer/routes/_authenticated/layout.tsxapps/docs/content/docs/cli/cli-reference.mdxpackages/cli/CLI_SPEC_CURRENT.mdpackages/cli/TODO.mdpackages/cli/package.jsonpackages/cli/src/commands/sidebar/groups/create/command.tspackages/cli/src/commands/sidebar/list/command.tspackages/cli/src/commands/sidebar/move/command.tspackages/cli/src/commands/sidebar/shared.test.tspackages/cli/src/commands/sidebar/shared.tspackages/client-state/README.mdpackages/client-state/package.jsonpackages/client-state/src/index.tspackages/client-state/src/schema.tspackages/client-state/src/sidebar.test.tspackages/client-state/src/sidebar.tspackages/client-state/src/store.test.tspackages/client-state/src/store.tspackages/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
| 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]); |
There was a problem hiding this comment.
🗄️ 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
| 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]); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Reconcile with server state instead of silently dropping failed/overwritten local edits.
Two related gaps here:
- On
replacefailure (line 116-121), onlyconsole.errorruns — no resync viasidebarState.get. The stalerevisionRefis 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
onChangedhandler (line 98-100) applies incoming snapshots unconditionally viaacceptDocument/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.
| 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.
| 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); | ||
| }); |
There was a problem hiding this comment.
🩺 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.tsRepository: 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:
- 1: https://nodejs.org/docs/latest-v5.x/api/fs.html
- 2: https://devcraftly.com/nodejs/watching-files/
- 3:
fs.watch()listener called withnullfilenameargument nodejs/node#61520 - 4: watch: clarify that the fileName parameter can be null nodejs/node#51305
- 5: https://stackoverflow.com/questions/9629307/fs-watch-is-returning-null-for-the-file-name
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.
Summary
superset sidebar list, group create/rename/delete/collapse/expand, and workspace move/ungroup commandsbun devCLI-to-CDP workflowArchitecture
A host can serve multiple clients, so it does not own their presentation preferences. State lives at:
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 lintbun run typecheck— 36/36 package tasksbun run test:cli-e2e— 8/8 assertions, 9 commandsbun devbundled CLI against Electron CDP on final commit83ec66e6eLocal 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
Bug Fixes
Documentation