Skip to content

feat(desktop): move a project to another organization - #6064

Open
ashbrener wants to merge 33 commits into
ParadevAI:mainfrom
ashbrener:cross-org-project-move
Open

ashbrener wants to merge 33 commits into
ParadevAI:mainfrom
ashbrener:cross-org-project-move

Conversation

@ashbrener

@ashbrener ashbrener commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #6063.

What this does

Adds Move to organization to a project's right-click menu. The repo lands in the other org with its worktrees, its branches and its place in the sidebar intact. Nothing is re-cloned and nothing on disk moves.

Why it needs three parts

Which org a repo belongs to is recorded in three places, and a move that touches only one of them half-works:

Where What it holds What happens if you skip it
Cloud (v2_projects + friends) the org id on the project, its workspaces, chat sessions, automations workspaces end up in a different org from their project, and nothing in the database objects
Local host database, one per org the project row the sidebar actually reads — there is no org column, the file is the org the repo simply doesn't appear in the destination
Sidebar state, stored per org collapse, order, groups, pane layout, pins the repo arrives stripped of everything you'd arranged

So the move is: start the destination host, move the cloud rows, re-register the project and each worktree, copy the sidebar state, then detach from the source.

The order matters

sequenceDiagram
    autonumber
    actor U as You
    participant App as Superset
    participant HB as Destination host
    participant DB as Cloud
    participant HA as Source host

    U->>App: Move to organization → picks one
    App->>HB: start host for that org
    Note over HB,DB: starting it registers this machine<br/>in the destination org — the cloud step<br/>can't re-point workspaces without that
    App->>DB: one transaction: project, workspaces,<br/>chat sessions, attachments, automations, runs
    App->>HB: re-register project (same id)
    App->>HB: adopt each worktree (same ids, same paths)
    App->>App: copy sidebar state (same group ids)
    App->>HA: detach — rows only
    Note over HA: never git worktree remove:<br/>those worktrees now belong to the other org
Loading
  1. Start the destination host first. That registers this machine in the destination org, which the cloud step needs before it can re-point the workspaces — otherwise it fails on the (organization_id, host_id) foreign key.
  2. Move the cloud rows — project, workspaces, chat sessions, attachments, automations and their runs, in one transaction.
  3. Re-register on the destination host, keeping the project id and each workspace id. Worktrees live under ~/.superset/worktrees/<projectId>/, so keeping the id means nothing on disk has to move.
  4. Copy the sidebar state, ids intact.
  5. Detach from the source last, through a new project.detach that removes rows only. The existing remove runs git worktree remove, which would delete the worktrees just adopted.

Ids: what has to stay the same, and why

Nothing here is copied. The same rows are re-registered somewhere else, because four different ids are load-bearing and each one strands something different if it changes.

flowchart LR
    P["project id"] --> D["worktrees on disk<br/>~/.superset/worktrees/&lt;projectId&gt;/…"]
    P --> CW["cloud workspaces<br/>v2_workspaces.project_id"]
    P --> SR["sidebar project row"]
    W["worktree workspace id"] --> PL["pane layout, open tabs"]
    W --> PIN["pinned state"]
    W --> HR["host workspace row"]
    M["checkout workspace id"] --> PL
    M --> MC["its cloud row"]
    S["group id"] --> GRP["which group each workspace sits in"]
Loading
Id Kept by What breaks if it changes
Project passing it to project.setup on the destination every worktree on disk is orphaned — they're stored under the project id
Worktree workspace workspaceCreation.adopt with existingWorkspaceId and the explicit path the worktree comes back as if new: no tabs, no layout, unpinned
The repo's own checkout the fix in this PR — project.setup now takes mainWorkspaceId same loss, plus its cloud row points at a workspace no host serves
Group (section) copied verbatim, ids and all every workspace lands ungrouped in the destination

Two more subtleties that only show up when you actually run it:

Removals are tombstones, not deletions. Two reconcilers re-add a worktree that has no local row, so removing a project marks its worktrees hidden instead of deleting them. That means moving a project back to an org meets its own tombstones — the host serves the worktrees, the sidebar suppresses them, and the repo arrives looking half-empty. The move now heals a tombstone for any workspace it's bringing in.

Pins are org-wide ordering, not a flag. pinnedAt orders the Pinned section across the whole org, so carrying the number over would jump a moved workspace ahead of pins already there. It's re-based against the destination.

Tasks stay behind. They're scoped to the org, not the project, so a moved workspace's task_id is cleared rather than left pointing across an org boundary.

What survives, and what doesn't

Survives: the repo, every worktree and its branch, the sidebar arrangement, per-project settings (worktree location, branch prefix).

Doesn't: running terminals and agent sessions — they belong to the source org's daemon and can't be re-parented. The dialog says so before you commit. The GitHub link is re-resolved in the destination org, or dropped if that org doesn't have the repo — a repo row is unique across the whole database and belongs to whichever org installed the app on it.

Only the machine you run it on moves. The host database is per machine, so another device keeps showing the repo under the old org until it runs the move too.

Walk-through

Before — side-project in the first org, with a feature/demo-move worktree:

Right-click gives the new item:

It lists the orgs you belong to, minus the one you're in:

Confirm step, saying plainly what happens:

After — the repo in the destination org:

Needs the API deployed

Worth flagging for anyone trying this from a client build: the two halves ship separately. The desktop side (menu, host re-registration, worktree adoption, sidebar state) is in the app, but v2Project.moveToOrganization runs on the API server. Until this is merged and deployed, a packaged client pointed at production gets No procedure found on path from that call — which is also a clean failure, since it happens before anything local is touched.

Projects created on a host have no cloud row and don't need the server at all; those move purely locally.

Testing

Driven through the real menus in a dev build, moving a project with a worktree between two orgs and back again, checking both host databases, the git worktree registrations and the sidebar state at each step.

Three bugs came out of running it, each fixed here with the reasoning in the commit:

  1. Projects created on a host are local-first and have no cloud row at all, so the move failed before doing any of the local work. It now reports the missing row and carries on.
  2. Re-registering minted a new id for the repo's own checkout, stranding the pane layout and pins keyed to the old one. The id is now carried across.
  3. Moving a project back to an org met the tombstones the earlier move left, so it arrived with its worktrees hidden. Those are now healed.

Unit tests: 8 on the sidebar state copy, 5 on the host detach — the detach tests use mocks that throw if git or the cloud is touched, so a regression fails loudly rather than quietly deleting a worktree.

bun run lint, bun run typecheck and the affected suites pass.

Not in this PR


Open in Stage

Summary by cubic

Adds a "Move to organization" option to a project's right-click menu. The move re-registers the project on the destination host and rows-only detaches it from the source, leaving worktrees and files on disk untouched — no reclone, no cloud dependency, and no server deploy required.

  • The destination host starts only if it's down; target orgs come from cloudTrpc.organization.list and exclude the active one.
  • project.detach drops the source host's rows in one transaction without calling git or the cloud, disposes PTYs, and is idempotent. It deliberately avoids main's new soft delete (restore/purge): a moved project must leave no restorable row behind.
  • The move keeps projectId, re-creates each local workspace under its existing id, adopts worktrees in place, preserves section ids, rebases pinnedAt, heals tombstones, and queues fresh terminals to reopen with empty panes.
  • The confirmation names running terminals per workspace; only the current device moves, and other devices keep the old org until moved there.
  • Failures unwind a half-registered destination, and a source cleanup miss surfaces as "moved, but not cleared from the old organization".

Written for commit 95ced8c. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Added “Move to organization” to the project context menu with destination selection.
    • Preserves project settings, workspace layout, and sidebar placement in the destination.
    • Includes confirmation, progress handling, and notifications for completed moves or skipped workspaces.
    • Disables the move option while an operation is in progress.
  • Bug Fixes

    • Improved cross-organization moves, including hidden workspace restoration and reliable cleanup.
    • Prevented duplicate sidebar entries during repeated move operations.

A project's organization is decided in three places at once: the cloud row,
the per-org host database that actually serves the sidebar, and the org-keyed
local placement rows. Moving one has to touch all three or it half-moves.

- `v2Project.moveToOrganization` re-keys the project, its workspaces, chat
  sessions, attachments, automations and runs in a single transaction. It
  checks membership in both orgs, pre-flights the slug and the destination's
  host registration so the workspace foreign key can't abort mid-transaction,
  and re-resolves the GitHub link in the target org rather than carrying an id
  that would silently resolve to nothing.
- `project.detach` on the host drops a project's rows without running
  `git worktree remove` and without the cloud delete, so the worktrees survive
  for the destination host to adopt.
- The renderer starts the destination host first (that registers the machine
  in the target org), moves the cloud rows, re-registers the project and each
  worktree with their existing ids and paths, copies the sidebar placement,
  then detaches from the source.

Project ids are preserved throughout: worktrees live under
`~/.superset/worktrees/<projectId>/`, so nothing on disk moves. Running
terminals and agent sessions do not survive — they belong to the source org's
pty daemon.
Projects created on a host mint their id locally and never write a cloud
row, so the move threw NOT_FOUND before doing any of the local work — the
part that actually decides which org a project belongs to. Report the
missing row instead and let the caller carry on.
Re-registering the project on the destination host minted a fresh main
workspace, so the checkout came back with a new id — stranding the pane
layout and pins keyed to the old one, and leaving its cloud row pointing
at a workspace no host serves. Pass the existing id through project.setup
and reuse it.
Removing a project tombstones its worktrees so they stay dismissed, so
moving one back met its own tombstones and landed with the worktrees
missing from the sidebar while the host still served them. Heal the
tombstone for any workspace the move brings in.
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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 end-to-end support for moving projects between organizations. The flow updates cloud records, prepares the destination host, preserves worktrees and sidebar state, detaches the source project, and adds sidebar controls.

Changes

Project move flow

Layer / File(s) Summary
Cloud project reassignment
packages/trpc/src/router/v2-project/v2-project.ts
Adds transactional organization reassignment for projects and related cloud records. It validates membership, hosts, slugs, and GitHub repository links.
Host setup and source detachment
packages/host-service/src/trpc/router/project/...
Preserves main workspace IDs during setup and adds transactional, idempotent source cleanup with session disposal, cache invalidation, and deletion events.
Sidebar state transfer
apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/...
Transfers project, section, and visible workspace state. It preserves target-relative ordering, pins, section links, tombstones, and idempotency.
Desktop move orchestration
apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/...
Coordinates destination host readiness, cloud movement, project setup, worktree adoption, sidebar migration, source removal, rollback, and skipped-workspace reporting.
Sidebar move controls
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/...
Adds organization selection, confirmation, progress state, and move submenus to collapsed and expanded project menus.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant ProjectMenu as DashboardSidebarProjectContextMenu
  participant MoveHook as useMoveProjectToOrganization
  participant CloudRouter as v2ProjectRouter.moveToOrganization
  participant TargetHost as target host service
  participant SourceHost as projectRouter.detach

  User->>ProjectMenu: select target organization
  ProjectMenu->>MoveHook: confirm project move
  MoveHook->>TargetHost: start and await readiness
  MoveHook->>CloudRouter: move project to target organization
  CloudRouter-->>MoveHook: return moved project and txid
  MoveHook->>TargetHost: setup project and adopt worktrees
  MoveHook->>SourceHost: detach source project
  SourceHost-->>MoveHook: return workspace IDs and warnings
  MoveHook-->>ProjectMenu: report success or skipped workspaces
Loading

Possibly related PRs

Suggested reviewers: kitenite

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 The implementation satisfies issue #6063 by preserving project, workspace, branch, sidebar, and identifier state during cross-organization moves.
Out of Scope Changes check ✅ Passed The code and tests remain focused on cross-organization project moves, including cloud migration, host cleanup, sidebar state, and related safeguards.
Title check ✅ Passed The title uses conventional commit format and clearly identifies the primary change: moving a desktop project to another organization.
Description check ✅ Passed The description thoroughly explains the change, rationale, implementation, testing, screenshots, limitations, and related issue.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@ghost

ghost commented Jul 30, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 5 individual chapters for you:

Title
1 Implement cloud-side project migration
2 Enable project detachment and ID preservation
3 Manage sidebar state during migration
4 Orchestrate the move project workflow
5 Wire move action to the sidebar UI
Open in Stage

Chapters generated by Stage for commit 78fe451 on Jul 30, 2026 7:59pm UTC.

@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 (3)
packages/host-service/src/trpc/router/project/project.ts (2)

845-855: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Warnings don't identify which workspace failed.

${killed.failed} terminal(s) may still be running is aggregated per workspace but carries no workspace name/id, so a user with several worktrees can't tell where to look. Including ws.name (or id) in both warning strings would make them actionable.

🤖 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/host-service/src/trpc/router/project/project.ts` around lines 845 -
855, Update the warning messages in the localWorkspaces loop around
disposeSessionsByWorkspaceId to include the affected workspace’s ws.name or
ws.id in both the killed-session warning and the disposal-failure warning, while
preserving the existing failure counts and error details.

857-904: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Consider running the local deletes in one SQLite transaction.

The session/binding/workspace/project deletes are independent statements, so a mid-loop failure throws INTERNAL_SERVER_ERROR after some rows are already gone — the project row can survive with its workspaces deleted, and the caller (which detaches last) has no way to roll that back. ctx.db.transaction(...) around the delete block would make the detach all-or-nothing while keeping the broadcasts after commit.

🤖 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/host-service/src/trpc/router/project/project.ts` around lines 857 -
904, The local detach operations in the try block are not atomic and can leave
partial deletion state after a failure. Wrap the terminal session, agent
binding, ACP session, local workspace, and project deletions in a single
ctx.db.transaction callback, preserving the existing per-row
deleteLocalWorkspace behavior; emit project-changed and perform label-cache
invalidation only after the transaction commits.
packages/host-service/src/trpc/router/project/project.test.ts (1)

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

Add a case for active terminal sessions.

All seeded sessions are disposed, so the ne(status, "active") filter in detach is never exercised: nothing here would catch a regression that deletes still-active rows the reaper needs to retry. Seeding one active session and asserting it survives (with originWorkspaceId nulled by the cascade) would cover that branch.

Also applies to: 124-182

🤖 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/host-service/src/trpc/router/project/project.test.ts` around lines
77 - 84, Extend the terminal-session test setup and assertions around the detach
flow to seed an additional session with status "active". Verify that detach
preserves this active row while the cascade clears its originWorkspaceId,
covering the ne(status, "active") branch without changing existing
disposed-session expectations.
🤖 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/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx`:
- Around line 70-90: Update the ContextMenuSubTrigger in
DashboardSidebarProjectContextMenu to include the existing disabled-state
styling used by menu items, while preserving its isMovingToOrganization disabled
behavior so the move entry visibly appears unavailable during an in-progress
move.

In
`@apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`:
- Around line 124-158: Update the post-move flow in useMoveProjectToOrganization
after v2Project.moveToOrganization succeeds to handle failures from
project.setup, setWorktreeBaseDir, or setBranchPrefix. Either compensate by
moving the cloud project back to the source organization before rethrowing, or
rethrow an explicit error stating that the project already moved and requires
setup in the destination organization; preserve the existing cleanup behavior.

In `@packages/trpc/src/router/v2-project/v2-project.ts`:
- Around line 477-491: The source-organization authorization must run before the
missing-cloud-row check in the project move flow. Update the logic around
getProjectAccess and the cloudRowMissing return so callers are validated against
source-org access first, while preserving the existing admin/ownership
requirements used by moveToOrganization and deletion for local-first projects.

---

Nitpick comments:
In `@packages/host-service/src/trpc/router/project/project.test.ts`:
- Around line 77-84: Extend the terminal-session test setup and assertions
around the detach flow to seed an additional session with status "active".
Verify that detach preserves this active row while the cascade clears its
originWorkspaceId, covering the ne(status, "active") branch without changing
existing disposed-session expectations.

In `@packages/host-service/src/trpc/router/project/project.ts`:
- Around line 845-855: Update the warning messages in the localWorkspaces loop
around disposeSessionsByWorkspaceId to include the affected workspace’s ws.name
or ws.id in both the killed-session warning and the disposal-failure warning,
while preserving the existing failure counts and error details.
- Around line 857-904: The local detach operations in the try block are not
atomic and can leave partial deletion state after a failure. Wrap the terminal
session, agent binding, ACP session, local workspace, and project deletions in a
single ctx.db.transaction callback, preserving the existing per-row
deleteLocalWorkspace behavior; emit project-changed and perform label-cache
invalidation only after the transaction commits.
🪄 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 Plus

Run ID: 4c9dee1d-ffa9-4ac9-9e6a-54fc601ededa

📥 Commits

Reviewing files that changed from the base of the PR and between 4a6c985 and c0502c4.

📒 Files selected for processing (11)
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/DashboardSidebarProjectSection.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.test.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts
  • packages/host-service/src/trpc/router/project/project.test.ts
  • packages/host-service/src/trpc/router/project/project.ts
  • packages/host-service/src/trpc/router/project/utils/ensure-main-workspace.ts
  • packages/trpc/src/router/v2-project/v2-project.ts

Comment on lines +477 to +491
const project = await dbWs.query.v2Projects.findFirst({
where: eq(v2Projects.id, input.id),
});
// Projects created on a host are local-first: the host mints the id
// and never writes a cloud row. There is then nothing here to re-key
// — which org such a project belongs to is decided entirely by the
// host database holding it — so report the no-op instead of failing
// and stranding the caller before it does the local move.
if (!project) {
return { project: null, txid: null, cloudRowMissing: true } as const;
}

await getProjectAccess(ctx.session.user.id, input.id, {
organizationId: sourceOrgId,
});

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.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -t f 'org-resource-access|access' packages/trpc/src --extension ts | head -20
rg -nP -C8 'export (async )?function requireOrgResourceAccess' packages/trpc/src
rg -nP -C3 'getProjectAccess\(' packages/trpc/src

Repository: superset-sh/superset

Length of output: 4342


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== v2-project outline/auth-related lines =="
ast-grep outline packages/trpc/src/router/v2-project/v2-project.ts --view compact | sed -n '1,220p' || true
sed -n '1,90p' packages/trpc/src/router/v2-project/v2-project.ts
sed -n '440,535p' packages/trpc/src/router/v2-project/v2-project.ts

echo "== org-resource-access implementation =="
sed -n '1,120p' packages/trpc/src/router/utils/org-resource-access.ts

echo "== project access helpers/usages =="
sed -n '1,80p' packages/trpc/src/router/project/project.ts
rg -n -C4 'getProjectAccess\(|verifyOrgOwner|verifyOrg|delete|detach|move' packages/trpc/src/router/v2-project packages/trpc/src/router/project packages/trpc/src/router/utils

Repository: superset-sh/superset

Length of output: 36098


Run source-org access checks before the cloudRowMissing probe, and keep admin ownership on move/delete semantics.

If cloudRowMissing returns before getProjectAccess, any org member can tell whether a project id is visible in the source organization. The existing moveToOrganization path already requires destination membership, but source ownership/intended policy may need to match the destructive move semantics rather than remaining a no-op for inaccessible local-first projects.

🤖 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/trpc/src/router/v2-project/v2-project.ts` around lines 477 - 491,
The source-organization authorization must run before the missing-cloud-row
check in the project move flow. Update the logic around getProjectAccess and the
cloudRowMissing return so callers are validated against source-org access first,
while preserving the existing admin/ownership requirements used by
moveToOrganization and deletion for local-first projects.

Once the cloud rows move, the project belongs to the destination org while
the local rows are still on the source host. A failure registering it there
left it split between the two with no sign of it. Move the cloud rows back,
and if that also fails say exactly what state the project is in and how to
finish it by hand. Also grey out the menu entry while a move is running.
@ashbrener

Copy link
Copy Markdown
Contributor Author

Thanks — two of the three are fixed in a16705c44.

Stranded between orgs after a partial failure. This was the one worth catching. Once the cloud rows move, the project belongs to the destination org while its local rows are still on the old host, and a failure in between left it that way with nothing on screen to say so. The destination steps are now wrapped: if any of them throw, the cloud rows are moved back and the original error surfaces. If the rollback itself also fails, the message says exactly what state the project is in and how to finish it by hand, instead of a bare error.

Disabled state on the menu entry. Added — it greys out while a move is running.

Access check before the missing-row probe. I've left this one, and here's why. That early return only fires when there is no v2_projects row for the id anywhere, which is the normal case for a project created on a host: the host mints the id locally and never writes a cloud row. There's nothing for getProjectAccess to check against, so running it first would throw NOT_FOUND for every local-first project and the move could never happen for them.

The write path is unchanged — the caller still has to be in the source org (it's their active org) and is checked against the destination before the probe runs. What's left is that someone in two orgs can learn whether a given project uuid has a cloud row. If you'd rather that stayed strict, I'm happy to gate the no-op on ownership of the destination org instead — say the word.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts (2)

212-230: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

No error handling after the target project is live — a failure here leaves the project duplicated across hosts silently.

Once the worktree adoption loop finishes, the target host already has a working project. If applyProjectSidebarState, navigateAwayFromWorkspace, removeProjectFromSidebar, or sourceClient.project.detach.mutate then throws, the function exits with a generic error while the project is fully set up on the destination and still registered (not detached) on the source — with no message telling the user this happened, unlike the explicit messaging built for the earlier undoCloudMove failure path.

Wrap this tail in a try/catch and surface a message explaining the project is available in the destination org but still needs to be detached from the source (or retry the detach) manually.

🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`
around lines 212 - 230, Wrap the post-adoption tail beginning with target
sidebar setup through sourceClient.project.detach.mutate in a try/catch. If
applyProjectSidebarState, workspace navigation, sidebar removal, or detachment
fails, surface an explicit error stating that the project is available in the
destination organization but remains attached to the source and requires
manually retrying detachment, matching the existing undoCloudMove failure
messaging pattern.

135-186: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

undoCloudMove doesn't clean up a partially-registered target host.

If project.setup.mutate succeeds but setWorktreeBaseDir or setBranchPrefix then throws, the destination host already holds a project registration (main workspace adopted under the preserved id) before undoCloudMove runs. The rollback only reverts the cloud row — it never detaches the stray registration from the target host. The rollback-failure message at Line 145 ("still set up on this device under the old one") then becomes inaccurate, since the target host now also has local state, and a later retry of the move could collide with this orphaned registration.

Track whether target setup succeeded and detach from the target host as part of the rollback.

🔧 Suggested fix
+				let targetSetupSucceeded = false;
 				const undoCloudMove = async (cause: unknown): Promise<never> => {
 					if (cloudMove.cloudRowMissing || !activeOrganizationId) throw cause;
 					try {
+						if (targetSetupSucceeded) {
+							await targetClient.project.detach
+								.mutate({ projectId })
+								.catch((detachError) =>
+									console.error(
+										"[move-project] failed to detach stray target registration",
+										detachError,
+									),
+								);
+						}
 						await apiTrpcClient.v2Project.moveToOrganization.mutate({
 							id: projectId,
 							targetOrganizationId: activeOrganizationId,
 						});
 					} catch (undoError) {
@@
 				try {
 					await targetClient.project.setup.mutate({
 						projectId,
 						...(mainWorkspaceId ? { mainWorkspaceId } : {}),
 						origin: { repoCloneUrl: project.repoUrl, name: project.name },
 						mode: { kind: "import", repoPath: project.repoPath },
 					});
+					targetSetupSucceeded = true;
 
 					// Per-project settings `project.setup` doesn't carry over.
 					if (project.worktreeBaseDir) {
🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`
around lines 135 - 186, Update undoCloudMove and the targetClient setup flow to
track whether project.setup.mutate completed; when later setup steps fail,
detach the partially registered project from the target host before or alongside
reverting the cloud move. Preserve the existing rollback behavior and error
propagation, but ensure cleanup failures are handled consistently and the
rollback-failure message accurately reflects any remaining target-host
registration.
🤖 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.

Outside diff comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`:
- Around line 212-230: Wrap the post-adoption tail beginning with target sidebar
setup through sourceClient.project.detach.mutate in a try/catch. If
applyProjectSidebarState, workspace navigation, sidebar removal, or detachment
fails, surface an explicit error stating that the project is available in the
destination organization but remains attached to the source and requires
manually retrying detachment, matching the existing undoCloudMove failure
messaging pattern.
- Around line 135-186: Update undoCloudMove and the targetClient setup flow to
track whether project.setup.mutate completed; when later setup steps fail,
detach the partially registered project from the target host before or alongside
reverting the cloud move. Preserve the existing rollback behavior and error
propagation, but ensure cleanup failures are handled consistently and the
rollback-failure message accurately reflects any remaining target-host
registration.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6e82ffec-66c2-4011-b32f-2d86165f9e84

📥 Commits

Reviewing files that changed from the base of the PR and between c0502c4 and a16705c.

📒 Files selected for processing (2)
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts

…up step

Two gaps the first rollback left. If project.setup succeeded and a later
settings call threw, the destination host kept a registration for a
project going back to the source org — the rollback now detaches it.
And the tail after adoption (sidebar copy, detach from source) had no
handling at all: by then the move has genuinely succeeded, so a failure
there is reported as "moved, but not cleared from the old organization"
rather than unwinding good work or reading like a failure.

Also on the host: detach's local deletes run in one transaction, so a
throw part way can't leave a project row whose workspaces are already
gone, and its warnings name the workspace they came from.
@ashbrener

Copy link
Copy Markdown
Contributor Author

Both of the new ones are fair, and both are fixed in bf6b8a182.

Rollback left a half-registered destination. If project.setup succeeded and setWorktreeBaseDir or setBranchPrefix then threw, the destination host kept a registration for a project that was going straight back to the source org — and the error text said the opposite. The rollback now tracks whether setup ran and detaches the destination before moving the cloud rows back. Detach touches rows only, so the worktrees are untouched either way.

No handling on the tail. By the time the sidebar copy and the source detach run, the move has genuinely happened: cloud rows moved, destination host registered, worktrees adopted. Unwinding good work over a failed cleanup would be worse than the failure. So that block now catches and reports what's actually true — the project moved, but it may still be listed in the old organization, and here's what to do about it — instead of surfacing something that reads like the move failed.

Also picked up two of the trivials on the host:

  • project.detach's local deletes now run in one transaction, so a throw part way through can't leave a project row whose workspaces are already gone.
  • Its warnings name the workspace they came from.

Left the third (the test seeds only disposed sessions, so the ne(status, "active") branch isn't exercised). It's a fair gap, but that branch is deliberately copied from workspaceCleanup.destroy and covering it means faking a failed kill, which mostly tests the mock. Happy to add it if you'd rather have it.

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

🧹 Nitpick comments (1)
packages/host-service/src/trpc/router/project/project.ts (1)

896-906: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Consider deferring the workspace deleted broadcasts until after the transaction commits.

deleteLocalWorkspace broadcasts workspace_deleted on the event bus from inside ctx.db.transaction(...). If a later statement in the same transaction throws (e.g. the projects delete), the rows roll back but renderers have already been told those workspaces are gone, so the sidebar shows a stale-deleted state until the next refetch — the exact half-state this transaction was added to prevent.

Collecting the ids inside the transaction and doing the DB delete + broadcasting after commit keeps the atomic guarantee and the notifications consistent.

🤖 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/host-service/src/trpc/router/project/project.ts` around lines 896 -
906, Update the project deletion transaction around deleteLocalWorkspace so it
collects local workspace IDs and performs database deletion without broadcasting
inside the transaction; after the transaction commits successfully, broadcast
each workspace_deleted event and invalidate its label cache. Preserve the
existing rollback behavior by ensuring no notifications occur if any
transactional statement fails.
🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`:
- Around line 251-260: Reorder the cleanup operations in the move flow so
sourceClient.project.detach.mutate({ projectId }) runs before
removeProjectFromSidebar(projectId). Keep the existing error handling and user
message unchanged, ensuring a detach failure leaves the sidebar row available
for the documented manual removal.

---

Nitpick comments:
In `@packages/host-service/src/trpc/router/project/project.ts`:
- Around line 896-906: Update the project deletion transaction around
deleteLocalWorkspace so it collects local workspace IDs and performs database
deletion without broadcasting inside the transaction; after the transaction
commits successfully, broadcast each workspace_deleted event and invalidate its
label cache. Preserve the existing rollback behavior by ensuring no
notifications occur if any transactional statement fails.
🪄 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 Plus

Run ID: b29c874d-a447-46dd-b7df-3a12dd18aa1d

📥 Commits

Reviewing files that changed from the base of the PR and between a16705c and bf6b8a1.

📒 Files selected for processing (2)
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts
  • packages/host-service/src/trpc/router/project/project.ts

… row

If the detach threw after the row was already gone, the error told the
user to remove a project from a sidebar it had just disappeared from.
The host database decides which org owns a project, so drop that first
and leave the sidebar entry as the visible remnant the message names.
@ashbrener

Copy link
Copy Markdown
Contributor Author

Good catch, and fixed in 78fe451e3 — swapped as suggested.

You're right that the message and the order contradicted each other: with the row removed first, a failing detach left the user reading "remove it from the old organization's sidebar" about something that was no longer in the sidebar. The host database is what decides which org owns a project, so that goes first now, and the sidebar entry is left as the visible thing the message actually points at.

# Conflicts:
#	apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/DashboardSidebarProjectSection.tsx
#	apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx
#	apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts (2)

183-187: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve the completed move status in the toast.

The orchestration can throw an error stating that the project moved successfully but source cleanup did not finish. This catch always displays Couldn't move the project, which presents a completed move as a failed move and can prompt an invalid retry.

Return a typed post-move cleanup result or select a warning state for cleanup-only failures.

The completion message originates in useMoveProjectToOrganization.ts.

🤖 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/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts`
around lines 183 - 187, Update the catch handling in
useDashboardSidebarProjectSectionActions to distinguish cleanup-only failures
from moves that did not complete, preserving the completed-move status when the
orchestration error indicates the project moved successfully but source cleanup
failed. Reuse the typed post-move cleanup result or warning state produced by
useMoveProjectToOrganization.ts, and show a warning-oriented toast instead of
“Couldn't move the project” for that case.

215-223: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not report unknown worktrees as tracked.

The filter intentionally excludes hosts where hasWorkspace is not false. When all values are unknown, untracked.length === 0 still displays All of this project's worktrees are already tracked. That statement is false and blocks import on older hosts.

Keep unknown tracking state separate and report that the host cannot determine tracked worktrees.

Suggested handling
+			const unknown = worktrees.some(
+				(worktree) =>
+					worktree.isMainWorktree === false &&
+					worktree.hasWorkspace !== false &&
+					worktree.hasWorkspace !== true,
+			);
+
 			if (untracked.length === 0) {
+				if (unknown) {
+					toast.info("This host cannot determine tracked worktrees");
+					return;
+				}
 				toast.info("All of this project's worktrees are already tracked");

The inline comment documents hosts that cannot report trackedness.

🤖 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/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts`
around lines 215 - 223, Update the worktree handling around the untracked filter
so unknown hasWorkspace values are tracked separately from confirmed tracked
worktrees. When no untracked worktrees exist but any worktree has an unknown
tracking state, report that the host cannot determine tracked worktrees and do
not claim all worktrees are already tracked; preserve the existing
already-tracked message only when every worktree is confirmed tracked.
apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts (4)

253-266: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Separate source-host cleanup errors from sidebar errors.

Keep the current detach-first order. The catch currently handles sourceClient.project.detach and removeProjectFromSidebar as one failure. If host detach fails, the source host still owns the project and workspace rows. Sidebar removal only changes sidebar state and cannot repair those rows.

Split these catches. Provide a retry or recovery path for host detach. Reserve the sidebar instruction for sidebar cleanup failures.

The sidebar mutation tests cover sidebar rows, not host database ownership.

🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`
around lines 253 - 266, Separate the cleanup handling around
sourceClient.project.detach and removeProjectFromSidebar while preserving their
current detach-first order. Add a retry or recovery path when detach fails, and
report that the source host still owns the project rather than presenting
sidebar-removal guidance. Keep the existing sidebar-specific instruction only
for failures from removeProjectFromSidebar, updating the related tests to cover
host-detach failure separately from sidebar cleanup failure.

108-124: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Align move eligibility with source-host ownership.

The move flow assumes the active local host owns the project, but the sidebar exposes the action for projects that may be served by another host.

  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts#L108-L124: resolve the project-serving host, or reject projects that are not served locally.
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts#L61-L80: hide the move targets for unsupported remote-only projects, or pass the required host context into orchestration.
🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`
around lines 108 - 124, Align move eligibility with project ownership: in
useMoveProjectToOrganization, resolve and use the host serving the project
before creating sourceClient, or reject projects not served by the local host.
In
apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts
lines 108-124, apply the source-host validation; in
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts
lines 61-80, hide move targets for unsupported remote-only projects or pass the
required host context into orchestration.

112-124: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Reacquire the source client after targeting the destination host.

getHostServiceClientByUrl caches per http://127.0.0.1:<port>; if targetOrganizationId re-adopts/reuses the active port, targetClient and sourceClient reference the same cached client. setHostServiceSecret then updates that URL’s secret, and later rollback targetClient.project.detach can run against the destination. Key clients by organization/connection identity, invalidate or reacquire sourceClient after targetHostUrl is obtained, and reapply its secret before cleanup.

🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`
around lines 112 - 124, The move flow must prevent sourceClient and targetClient
from sharing a cached client when waitForTargetHost reuses the active port.
Update the logic around getHostServiceClientByUrl, waitForTargetHost, and
setHostServiceSecret to identify clients by organization/connection identity or
invalidate and reacquire sourceClient after targetHostUrl is resolved, then
restore the source client’s secret before rollback or cleanup.

137-167: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make destination rollback state-aware.

Set up rollback state from project.setup, then call project.detach during recovery. Keep destination cleanup failures out of the rollback path, but include them in the final recovery message. project.detach is idempotent no-op when the destination host does not yet serve the project, so the cleanup can be unconditional.

🤖 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/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`
around lines 137 - 167, Make undoCloudMove state-aware using the result of
targetClient.project.setup, then invoke targetClient.project.detach
unconditionally during recovery because it is idempotent. Capture any detach
failure without interrupting rollback, and include that failure alongside the
original error in the final recovery message while preserving the existing cloud
rollback behavior.
🤖 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.

Outside diff comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts`:
- Around line 183-187: Update the catch handling in
useDashboardSidebarProjectSectionActions to distinguish cleanup-only failures
from moves that did not complete, preserving the completed-move status when the
orchestration error indicates the project moved successfully but source cleanup
failed. Reuse the typed post-move cleanup result or warning state produced by
useMoveProjectToOrganization.ts, and show a warning-oriented toast instead of
“Couldn't move the project” for that case.
- Around line 215-223: Update the worktree handling around the untracked filter
so unknown hasWorkspace values are tracked separately from confirmed tracked
worktrees. When no untracked worktrees exist but any worktree has an unknown
tracking state, report that the host cannot determine tracked worktrees and do
not claim all worktrees are already tracked; preserve the existing
already-tracked message only when every worktree is confirmed tracked.

In
`@apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts`:
- Around line 253-266: Separate the cleanup handling around
sourceClient.project.detach and removeProjectFromSidebar while preserving their
current detach-first order. Add a retry or recovery path when detach fails, and
report that the source host still owns the project rather than presenting
sidebar-removal guidance. Keep the existing sidebar-specific instruction only
for failures from removeProjectFromSidebar, updating the related tests to cover
host-detach failure separately from sidebar cleanup failure.
- Around line 108-124: Align move eligibility with project ownership: in
useMoveProjectToOrganization, resolve and use the host serving the project
before creating sourceClient, or reject projects not served by the local host.
In
apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts
lines 108-124, apply the source-host validation; in
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts
lines 61-80, hide move targets for unsupported remote-only projects or pass the
required host context into orchestration.
- Around line 112-124: The move flow must prevent sourceClient and targetClient
from sharing a cached client when waitForTargetHost reuses the active port.
Update the logic around getHostServiceClientByUrl, waitForTargetHost, and
setHostServiceSecret to identify clients by organization/connection identity or
invalidate and reacquire sourceClient after targetHostUrl is resolved, then
restore the source client’s secret before rollback or cleanup.
- Around line 137-167: Make undoCloudMove state-aware using the result of
targetClient.project.setup, then invoke targetClient.project.detach
unconditionally during recovery because it is idempotent. Capture any detach
failure without interrupting rollback, and include that failure alongside the
original error in the final recovery message while preserving the existing cloud
rollback behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ec80a1e2-d821-4a57-bd1f-4443a3a3fabf

📥 Commits

Reviewing files that changed from the base of the PR and between 78fe451 and acbf04c.

📒 Files selected for processing (4)
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/DashboardSidebarProjectSection.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts
  • apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/DashboardSidebarProjectSection.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx

The move re-registered the project on the destination org's host AND
re-keyed the cloud rows. Drop the cloud half.

`plans/remove-cloud-project-model.md` retires `v2_projects` and the
`v2Project` router, so which org owns a project is becoming host-local by
design — adding `moveToOrganization` to that router was building on ground
already scheduled to go. Doing it locally also means the move works without
waiting for a server deploy, and nothing on the source changes until the
final detach, so a failure part-way leaves the project where it started
instead of split across two orgs.

Residue: a moved workspace's `v2_workspaces` row keeps the old
organization_id until those tables are retired. It doesn't surface in the
sidebar, which reads the host fan-out.

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 10 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx">

<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx:78">
P2: A project can still be removed from the source sidebar while its move is running because this only disables the move submenu; `Remove from Sidebar` remains active. Since `moveProjectToOrganization` copies sidebar state after destination setup, that concurrent removal can leave the destination project registered but missing from the sidebar; gating the full project menu or all project-mutating actions during `isMovingToOrganization` would avoid the race.</violation>
</file>

<file name="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts">

<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts:84">
P3: The pin re-base assigns destination pinnedAt values sequentially in the iteration order of the source workspace Map (state.workspaces), not in the source's actual pinnedAt ordering. collectProjectSidebarState builds that array with Array.from(...state.values()).filter(...), which preserves source Map insertion/creation order — and that order diverges from pinnedAt whenever a user re-pins/reorders workspaces without recreating rows. Consequence: after a move, the relative ordering of that project's pinned workspaces in the destination Pinned section can be shuffled, even though the surrounding code's intent (per the doc comment and the 're-bases a pin above the target org's existing pins' test) is to preserve source pin order. Sorting state.workspaces by source pinnedAt before assigning sequential destination values would make the rebase faithful to the actual pin semantics.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant U as User
    participant UI as Project Context Menu
    participant MV as Move Project Flow
    participant CO as Host Service Coordinator
    participant SH as Source Org Host
    participant DH as Destination Org Host
    participant SB as Sidebar State (per-org collections)
    participant PT as PTY Daemon

    note over SH,DH: Separate per-org host processes and SQLite databases on the same machine
    note over MV,DH: The org that owns a project is whichever host DB holds its row, the cloud is not consulted

    U->>UI: Right-click project -> Move to organization -> pick org
    UI->>MV: moveProjectToOrganization(projectId, targetOrganizationId)
    MV->>SH: project.get + workspace.list
    SH-->>MV: project and its workspaces
    MV->>CO: restart host service for target org
    CO-->>MV: target host loopback URL + secret
    MV->>DH: project.setup(projectId, mainWorkspaceId, origin, mode=import)
    DH-->>MV: project registered with same project id and repo path
    MV->>DH: setWorktreeBaseDir / setBranchPrefix (per-project settings)
    loop each worktree workspace
        MV->>DH: workspaceCreation.adopt(existingWorkspaceId, worktreePath, branch)
    end
    alt a worktree cannot be adopted
        MV->>MV: record workspace name in skippedWorkspaces
    end
    MV->>SB: collect project sidebar state from source org
    SB-->>MV: project, section, and workspace rows
    MV->>SB: preload target org collections, then applyProjectSidebarState
    note over SB: Sidebar ids are preserved, tabOrder and pinnedAt are re-based against the target org, hidden tombstones are healed
    MV->>MV: navigate open workspaces away before source rows disappear
    MV->>SH: project.detach(projectId)
    SH->>PT: disposeSessionsByWorkspaceId(workspaceIds)
    PT-->>SH: terminal sessions disposed
    note over SH: Rows only — no git worktree remove and no cloud delete
    SH-->>MV: detach result with warnings
    alt source cleanup fails after a successful move
        MV-->>UI: warning: moved, but still listed in the old organization
    else move succeeds
        MV-->>UI: success toast, including any skipped workspaces
    end
Loading

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

Re-trigger cubic

<ContextMenuSeparator />
<ContextMenuSub>
<ContextMenuSubTrigger
disabled={isMovingToOrganization}

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.

P2: A project can still be removed from the source sidebar while its move is running because this only disables the move submenu; Remove from Sidebar remains active. Since moveProjectToOrganization copies sidebar state after destination setup, that concurrent removal can leave the destination project registered but missing from the sidebar; gating the full project menu or all project-mutating actions during isMovingToOrganization would avoid the race.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx, line 78:

<comment>A project can still be removed from the source sidebar while its move is running because this only disables the move submenu; `Remove from Sidebar` remains active. Since `moveProjectToOrganization` copies sidebar state after destination setup, that concurrent removal can leave the destination project registered but missing from the sidebar; gating the full project menu or all project-mutating actions during `isMovingToOrganization` would avoid the race.</comment>

<file context>
@@ -54,6 +70,30 @@ export function DashboardSidebarProjectContextMenu({
+						<ContextMenuSeparator />
+						<ContextMenuSub>
+							<ContextMenuSubTrigger
+								disabled={isMovingToOrganization}
+								className="data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
+							>
</file context>

let nextPinnedAt = getNextPinnedAt(collections);
for (const row of state.workspaces) {
if (row.sidebarState.isHidden) continue;
const pinnedAt = row.sidebarState.pinnedAt == null ? null : nextPinnedAt++;

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.

P3: The pin re-base assigns destination pinnedAt values sequentially in the iteration order of the source workspace Map (state.workspaces), not in the source's actual pinnedAt ordering. collectProjectSidebarState builds that array with Array.from(...state.values()).filter(...), which preserves source Map insertion/creation order — and that order diverges from pinnedAt whenever a user re-pins/reorders workspaces without recreating rows. Consequence: after a move, the relative ordering of that project's pinned workspaces in the destination Pinned section can be shuffled, even though the surrounding code's intent (per the doc comment and the 're-bases a pin above the target org's existing pins' test) is to preserve source pin order. Sorting state.workspaces by source pinnedAt before assigning sequential destination values would make the rebase faithful to the actual pin semantics.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts, line 84:

<comment>The pin re-base assigns destination pinnedAt values sequentially in the iteration order of the source workspace Map (state.workspaces), not in the source's actual pinnedAt ordering. collectProjectSidebarState builds that array with Array.from(...state.values()).filter(...), which preserves source Map insertion/creation order — and that order diverges from pinnedAt whenever a user re-pins/reorders workspaces without recreating rows. Consequence: after a move, the relative ordering of that project's pinned workspaces in the destination Pinned section can be shuffled, even though the surrounding code's intent (per the doc comment and the 're-bases a pin above the target org's existing pins' test) is to preserve source pin order. Sorting state.workspaces by source pinnedAt before assigning sequential destination values would make the rebase faithful to the actual pin semantics.</comment>

<file context>
@@ -0,0 +1,118 @@
+	let nextPinnedAt = getNextPinnedAt(collections);
+	for (const row of state.workspaces) {
+		if (row.sidebarState.isHidden) continue;
+		const pinnedAt = row.sidebarState.pinnedAt == null ? null : nextPinnedAt++;
+		const existing = collections.v2WorkspaceLocalState.get(row.workspaceId);
+		if (!existing) {
</file context>

… after a move

`restart` is stop-then-start, so bringing up the destination host killed the
terminals and agent sessions of every other project in that organization
when its host was already running. Resolve the connection first and start
only a host that is actually down.

The moved project also took up to 30s to appear, because the project list
polls its hosts on a fallback interval and nothing invalidated it — so
invalidate the host project and workspace queries once the move lands.

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts">

<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts:274">
P2: The move can leave the new-workspace project setup check showing stale membership: the newly added invalidation only refreshes the `host-service/...` queries, while `useHostProjectIds` reads a separate `project/list` cache that is not invalidated. Invalidating the legacy project-list key as part of this refresh would make the destination project immediately usable there too.</violation>

<violation number="2" location="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts:278">
P2: If post-move cleanup fails after the destination has been registered, these refreshes are skipped because the cleanup catch throws before reaching them. The UI can then continue showing stale source/destination project and workspace lists; refreshing the relevant caches from the cleanup-failure path as well would match the "moved successfully" error state.</violation>
</file>

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

Re-trigger cubic

Comment on lines +274 to +276
void queryClient.invalidateQueries({
queryKey: ["host-service", "projects", "list"],
});

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.

P2: The move can leave the new-workspace project setup check showing stale membership: the newly added invalidation only refreshes the host-service/... queries, while useHostProjectIds reads a separate project/list cache that is not invalidated. Invalidating the legacy project-list key as part of this refresh would make the destination project immediately usable there too.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts, line 274:

<comment>The move can leave the new-workspace project setup check showing stale membership: the newly added invalidation only refreshes the `host-service/...` queries, while `useHostProjectIds` reads a separate `project/list` cache that is not invalidated. Invalidating the legacy project-list key as part of this refresh would make the destination project immediately usable there too.</comment>

<file context>
@@ -251,6 +268,16 @@ export function useMoveProjectToOrganization() {
+				// The project list polls its hosts on a 30s fallback interval, so
+				// without this the moved project takes up to half a minute to
+				// appear in the destination (and to leave the source).
+				void queryClient.invalidateQueries({
+					queryKey: ["host-service", "projects", "list"],
+				});
</file context>
Suggested change
void queryClient.invalidateQueries({
queryKey: ["host-service", "projects", "list"],
});
void queryClient.invalidateQueries({
queryKey: ["host-service", "projects", "list"],
});
void queryClient.invalidateQueries({
queryKey: ["project", "list"],
});

queryKey: ["host-service", "projects", "list"],
});
void queryClient.invalidateQueries({
queryKey: ["host-service", "workspaces", "list"],

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.

P2: If post-move cleanup fails after the destination has been registered, these refreshes are skipped because the cleanup catch throws before reaching them. The UI can then continue showing stale source/destination project and workspace lists; refreshing the relevant caches from the cleanup-failure path as well would match the "moved successfully" error state.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts, line 278:

<comment>If post-move cleanup fails after the destination has been registered, these refreshes are skipped because the cleanup catch throws before reaching them. The UI can then continue showing stale source/destination project and workspace lists; refreshing the relevant caches from the cleanup-failure path as well would match the "moved successfully" error state.</comment>

<file context>
@@ -251,6 +268,16 @@ export function useMoveProjectToOrganization() {
+					queryKey: ["host-service", "projects", "list"],
+				});
+				void queryClient.invalidateQueries({
+					queryKey: ["host-service", "workspaces", "list"],
+				});
+
</file context>

… org

A moved workspace arrived with its pane layout intact, but the panes point
at PTY sessions owned by the source org's daemon — which the move disposes
and which the destination host has never heard of. The result is a terminal
stuck on "Disconnected" whose Reconnect can never succeed.

Start the moved workspace with an empty layout instead, and drop the
run-terminal and pending-migrated-terminal state with it. Agent history is
keyed by directory and the paths don't move, so `claude --resume` still
finds the session.
…r side

Two halves of the same problem: the terminals in a moved project die with
the source org's daemon, and the confirmation said so in the abstract.

The dialog now asks the source host what is actually running first, and
names it — "3 running terminals (main, review) will be closed and re-opened
on the other side". A project with nothing running says so instead, because
a warning that always fires is one people learn to click through.

The sessions are then queued to come back: their workspaces are recorded
before the detach and seeded into `pendingMigratedTerminals`, the same queue
the v1→v2 migration uses, so opening the moved workspace spawns fresh shells
in the right directories with panes adopted. What can't survive is anything
mid-run — hence telling the user before, not just restoring after.

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 3 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts">

<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts:167">
P2: A failed impact preflight silently removes the warning, so users can approve a move that closes running terminal/agent sessions without being told. Logging the preflight failure and showing a conservative fallback warning would preserve safety when host/session inspection is unavailable.

(Based on your team's feedback about handling async failures and preserving diagnostic visibility.)</violation>
</file>

<file name="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts">

<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts:157">
P2: A terminal-list failure produces false reassurance and can lose live shells: the workspace is treated as having no terminals, then the move proceeds without re-opening them. Surfacing an unknown impact and requiring a retry, or otherwise aborting when a workspace cannot be inspected, would avoid silently dropping sessions.</violation>
</file>

<file name="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts">

<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts:108">
P3: The new terminal-reopen behavior isn't covered by the unit tests. All applyProjectSidebarState cases call the function without terminalsToReopen, so nothing asserts that pendingMigratedTerminals is now seeded from the map on insert or on tombstone healing. Since this module exists specifically to be unit-tested against in-memory collections, adding a case that passes a terminalsToReopen map (one workspace with entries, one without) and asserting the resulting pendingMigratedTerminals values on both the fresh row and the healed tombstone would lock in the behavior the move flow now depends on.</violation>
</file>

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

Re-trigger cubic

Comment on lines +167 to +173
const impact = await getMoveImpact(project.id).catch(() => null);
const terminalWarning =
impact && impact.terminalCount > 0
? ` ${impact.terminalCount} running terminal${impact.terminalCount === 1 ? "" : "s"} (${impact.workspacesWithTerminals.join(", ")}) will be closed and re-opened on the other side — anything mid-run stops, so save or hand off first.`
: impact
? " Nothing is running in it right now."
: "";

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.

P2: A failed impact preflight silently removes the warning, so users can approve a move that closes running terminal/agent sessions without being told. Logging the preflight failure and showing a conservative fallback warning would preserve safety when host/session inspection is unavailable.

(Based on your team's feedback about handling async failures and preserving diagnostic visibility.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts, line 167:

<comment>A failed impact preflight silently removes the warning, so users can approve a move that closes running terminal/agent sessions without being told. Logging the preflight failure and showing a conservative fallback warning would preserve safety when host/session inspection is unavailable.

(Based on your team's feedback about handling async failures and preserving diagnostic visibility.) </comment>

<file context>
@@ -153,15 +156,24 @@ export function useDashboardSidebarProjectSectionActions({
+		// Ask what is actually running before warning about it. A blanket
+		// "terminals will close" on a project with nothing open teaches people
+		// to click through the one time it matters.
+		const impact = await getMoveImpact(project.id).catch(() => null);
+		const terminalWarning =
+			impact && impact.terminalCount > 0
</file context>
Suggested change
const impact = await getMoveImpact(project.id).catch(() => null);
const terminalWarning =
impact && impact.terminalCount > 0
? ` ${impact.terminalCount} running terminal${impact.terminalCount === 1 ? "" : "s"} (${impact.workspacesWithTerminals.join(", ")}) will be closed and re-opened on the other side — anything mid-run stops, so save or hand off first.`
: impact
? " Nothing is running in it right now."
: "";
const impact = await getMoveImpact(project.id).catch((error) => {
console.warn("[move-project] failed to get move impact", error);
return null;
});
const terminalWarning =
impact && impact.terminalCount > 0
? ` ${impact.terminalCount} running terminal${impact.terminalCount === 1 ? "" : "s"} (${impact.workspacesWithTerminals.join(", ")}) will be closed and re-opened on the other side — anything mid-run stops, so save or hand off first.`
: impact
? " Nothing is running in it right now."
: " Running terminals and agent sessions may be closed and re-opened on the other side — anything mid-run stops, so save or hand off first.";

terminalIds: live,
});
}
} catch (error) {

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.

P2: A terminal-list failure produces false reassurance and can lose live shells: the workspace is treated as having no terminals, then the move proceeds without re-opening them. Surfacing an unknown impact and requiring a retry, or otherwise aborting when a workspace cannot be inspected, would avoid silently dropping sessions.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/useMoveProjectToOrganization.ts, line 157:

<comment>A terminal-list failure produces false reassurance and can lose live shells: the workspace is treated as having no terminals, then the move proceeds without re-opening them. Surfacing an unknown impact and requiring a retry, or otherwise aborting when a workspace cannot be inspected, would avoid silently dropping sessions.</comment>

<file context>
@@ -117,6 +125,71 @@ export function useMoveProjectToOrganization() {
+							terminalIds: live,
+						});
+					}
+				} catch (error) {
+					// A host that can't answer shouldn't block the move; the worst
+					// case is a quieter warning and no terminals queued back.
</file context>

// so `claude --resume` still finds it.
paneLayout: createEmptyPaneLayout(),
workspaceRunTerminals: {},
pendingMigratedTerminals: terminalsToReopen.get(row.workspaceId) ?? [],

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.

P3: The new terminal-reopen behavior isn't covered by the unit tests. All applyProjectSidebarState cases call the function without terminalsToReopen, so nothing asserts that pendingMigratedTerminals is now seeded from the map on insert or on tombstone healing. Since this module exists specifically to be unit-tested against in-memory collections, adding a case that passes a terminalsToReopen map (one workspace with entries, one without) and asserting the resulting pendingMigratedTerminals values on both the fresh row and the healed tombstone would lock in the behavior the move flow now depends on.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/hooks/useMoveProjectToOrganization/moveProjectSidebarState.ts, line 108:

<comment>The new terminal-reopen behavior isn't covered by the unit tests. All applyProjectSidebarState cases call the function without terminalsToReopen, so nothing asserts that pendingMigratedTerminals is now seeded from the map on insert or on tombstone healing. Since this module exists specifically to be unit-tested against in-memory collections, adding a case that passes a terminalsToReopen map (one workspace with entries, one without) and asserting the resulting pendingMigratedTerminals values on both the fresh row and the healed tombstone would lock in the behavior the move flow now depends on.</comment>

<file context>
@@ -95,7 +105,7 @@ export function applyProjectSidebarState(
 				paneLayout: createEmptyPaneLayout(),
 				workspaceRunTerminals: {},
-				pendingMigratedTerminals: [],
+				pendingMigratedTerminals: terminalsToReopen.get(row.workspaceId) ?? [],
 				sidebarState: { ...row.sidebarState, pinnedAt },
 			});
</file context>

The warning read "3 running terminals (account-bootstrap, render-run)",
which looks like it is naming the terminals and coming up one short. Those
are workspace names, and the count spans them.

Break it down per workspace — "account-bootstrap (2), render-run (1)" — so
the total is accounted for, and say that some may be running in the
background with no pane open, which is where a terminal you can't see is
hiding.
…field

ParadevAI#6341 folded terminal.listSessions into terminal.list, and the pending
migrated-terminal row gained v1PaneId. A shell re-opened in the
destination org is a fresh terminal, so it carries none.
- acpSessions is gone from the host schema; detach no longer clears it.
- The organizations collection went with Electric (ParadevAI#6328); the move-to-org
  menu reads cloudTrpc.organization.list instead.
ParadevAI#6434 deleted the ACP sessions stack, taking `acpSessions` out of the
host-service schema. This test still seeded and asserted on it, so every
detach case died in the fixture on `schema.acpSessions` being undefined
rather than on anything it was meant to check.

The production detach path never referenced the table, so this is only the
fixture catching up. `terminalAgentBindings` and `terminalSessions` still
cover the no-foreign-key tables the project cascade can't reach.
# Conflicts:
#	apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/components/DashboardSidebarProjectContextMenu/DashboardSidebarProjectContextMenu.tsx
# Conflicts:
#	packages/i18n/locales/cs/messages.ts
#	packages/i18n/locales/de/messages.ts
#	packages/i18n/locales/en/messages.ts
#	packages/i18n/locales/es/messages.ts
#	packages/i18n/locales/fr/messages.ts
#	packages/i18n/locales/id/messages.ts
#	packages/i18n/locales/it/messages.ts
#	packages/i18n/locales/ja/messages.ts
#	packages/i18n/locales/ko/messages.ts
#	packages/i18n/locales/nl/messages.ts
#	packages/i18n/locales/pl/messages.ts
#	packages/i18n/locales/pt-BR/messages.ts
#	packages/i18n/locales/ru/messages.ts
#	packages/i18n/locales/tr/messages.ts
#	packages/i18n/locales/vi/messages.ts
#	packages/i18n/locales/zh-CN/messages.ts
#	packages/i18n/locales/zh-TW/messages.ts
# Conflicts:
#	apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/DashboardSidebarProjectSection.tsx
#	apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarProjectSection/hooks/useDashboardSidebarProjectSectionActions/useDashboardSidebarProjectSectionActions.ts
#	packages/host-service/src/trpc/router/project/project.ts
#	packages/i18n/locales/cs/messages.po
#	packages/i18n/locales/cs/messages.ts
#	packages/i18n/locales/de/messages.po
#	packages/i18n/locales/de/messages.ts
#	packages/i18n/locales/en/messages.po
#	packages/i18n/locales/en/messages.ts
#	packages/i18n/locales/es/messages.po
#	packages/i18n/locales/es/messages.ts
#	packages/i18n/locales/fr/messages.po
#	packages/i18n/locales/fr/messages.ts
#	packages/i18n/locales/id/messages.po
#	packages/i18n/locales/id/messages.ts
#	packages/i18n/locales/it/messages.po
#	packages/i18n/locales/it/messages.ts
#	packages/i18n/locales/ja/messages.po
#	packages/i18n/locales/ja/messages.ts
#	packages/i18n/locales/ko/messages.po
#	packages/i18n/locales/ko/messages.ts
#	packages/i18n/locales/nl/messages.po
#	packages/i18n/locales/nl/messages.ts
#	packages/i18n/locales/pl/messages.po
#	packages/i18n/locales/pl/messages.ts
#	packages/i18n/locales/pt-BR/messages.po
#	packages/i18n/locales/pt-BR/messages.ts
#	packages/i18n/locales/ru/messages.po
#	packages/i18n/locales/ru/messages.ts
#	packages/i18n/locales/tr/messages.po
#	packages/i18n/locales/tr/messages.ts
#	packages/i18n/locales/vi/messages.po
#	packages/i18n/locales/vi/messages.ts
#	packages/i18n/locales/zh-CN/messages.po
#	packages/i18n/locales/zh-CN/messages.ts
#	packages/i18n/locales/zh-TW/messages.po
#	packages/i18n/locales/zh-TW/messages.ts
Main removed the implicit main workspace (ParadevAI#7485): ensure-main-workspace.ts is
gone and a project's checkout now carries any number of "local" workspaces,
created through workspaces.createLocal with an optional caller-supplied id.

The move now drops the mainWorkspaceId passthrough on project.setup and
re-creates each local workspace on the destination host under its existing id,
the same way worktrees were already adopted. Every local workspace keeps its
pane layout and pins, not only the first. Sidebar removal on the source org
keys off "local" instead of the retired "main" type.

Claude-Session: https://claude.ai/code/session_01HJHZG8HzXXCb5Z5eyt5kj5
Main moved project deletion to soft delete with restore and purge. project.detach
stays separate: a move must drop the source rows without leaving a restorable
deleted project behind and without touching the worktrees.

Claude-Session: https://claude.ai/code/session_01GjegunzxDV6phC9APFLdX9
Main generates locales/*/messages.ts at build time since ParadevAI#7180. The merge
commit picked up the locally generated copies.

Claude-Session: https://claude.ai/code/session_01GjegunzxDV6phC9APFLdX9

This branch has not been deployed

No deployments
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.

[feat] Move a project to a different organization

1 participant