From b2faf3b2a69515a33e027125d3675ec6a8616bfc Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:43:21 +0200 Subject: [PATCH] =?UTF-8?q?fix(modules):=20round-1=20bug-hunt=20fixes=20?= =?UTF-8?q?=E2=80=94=20project=20re-add=20wipe,=20worktree=20collision=20(?= =?UTF-8?q?rework=20of=20#297)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/SessionSidebar.tsx | 11 +----- lib/hosts/session-ops.ts | 2 +- lib/project-ordering.test.mjs | 17 ++++++++ lib/project-ordering.ts | 9 ++++- lib/project-registry.test.mjs | 32 +++++++++++++++ lib/project-registry.ts | 29 ++++++++++++-- lib/workspace-memory.test.mjs | 37 ++++++------------ lib/workspace-memory.ts | 73 +++++++---------------------------- lib/worktree.test.mjs | 40 +++++++++++++++++++ lib/worktree.ts | 45 ++++++++++++++++++++- 10 files changed, 193 insertions(+), 102 deletions(-) diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index eaad099ee..82ba17977 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -9,7 +9,7 @@ import { ProjectLaunchConfigDialog } from "./ProjectLaunchConfigDialog"; import { ProviderUsageBar } from "./ProviderUsageBar"; import { Tooltip } from "./ui/primitives"; import { toast } from "./ui/toast"; -import { clearLastOpenSession, setLastOpenSession, workspaceKeyOf } from "@/lib/workspace-memory"; +import { workspaceKeyOf } from "@/lib/workspace-memory"; import { LOCAL_HOST_ID, foldedHostProjectKey, groupProjectsByHost, groupSessionsByProject, hostProjectKey, projectIdentity, projectTargetId, nextPinOrder, orderProjects, projectActivityCounts, remoteHostId, type ProjectSortMode } from "@/lib/project-ordering"; import { isLinkUp } from "@/lib/hosts/host"; import { useHostRows } from "@/hooks/useHostRows"; @@ -1475,16 +1475,9 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, // Stable callbacks for the session list so memoized children don't re-render // on every parent state change. const handleSessionDeleted = useCallback((id: string) => { - const deleted = allSessions.find((session) => session.id === id); - if (deleted) clearLastOpenSession(hostProjectKey(deleted.hostId, workspaceKeyOf(deleted))); onSessionDeleted?.(id); loadSessions(); - }, [allSessions, onSessionDeleted, loadSessions]); - - useEffect(() => { - const selected = allSessions.find((session) => session.id === selectedSessionId); - if (selected) setLastOpenSession(hostProjectKey(selected.hostId, workspaceKeyOf(selected)), selected.id); - }, [allSessions, selectedSessionId]); + }, [onSessionDeleted, loadSessions]); return (
diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index 66580dc17..2747cbca2 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -704,7 +704,7 @@ export const sessionOps: SessionOps = { const next = upsertProject(loadProjectRegistry(), projectRoot, new Date().toISOString(), launchConfig); saveProjectRegistry(next); const entry = next.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(projectRoot))!; - return ok({ path: entry.path, addedAt: entry.addedAt, launchConfig: entry.launchConfig }); + return ok({ path: entry.path, addedAt: entry.addedAt, alias: entry.alias, sortOrder: entry.sortOrder, pinOrder: entry.pinOrder, launchConfig: entry.launchConfig }); } catch (error) { if (error instanceof ProjectPathError) return fail(400, error.code, error.message); throw error; diff --git a/lib/project-ordering.test.mjs b/lib/project-ordering.test.mjs index 14c3b5fb4..8cf667707 100644 --- a/lib/project-ordering.test.mjs +++ b/lib/project-ordering.test.mjs @@ -94,6 +94,23 @@ test("groups sessions under their project, including worktree sessions", () => { assert.deepEqual(grouped.get("/other").map((s) => s.id).sort(), ["fork", "parent"]); }); +test("session with no workspace key at all is skipped, not bucketed", () => { + // Deliberately no "unknown workspace" bucket: the sidebar renders one row + // per project (it iterates projects, never this map's keys), so a bucket + // keyed "" would be unreachable dead data. A session that carries a key in + // any field still groups via workspaceKeyOf's empty-string fallthrough; + // only a header with no location at all has nowhere to go. + const projects = [{ path: "/proj/a" }]; + const sessions = [ + session("s1", { cwd: "", projectRoot: "", projectKey: "" }), + session("s2", { cwd: "/proj/a", projectRoot: "/proj/a", projectKey: "/proj/a" }), + ]; + const grouped = groupSessionsByProject(projects, sessions); + assert.deepEqual(grouped.get("/proj/a").map((s) => s.id), ["s2"]); + assert.equal([...grouped.values()].flat().some((s) => s.id === "s1"), false); + assert.equal(grouped.has(""), false); +}); + test("projectActivityCounts tallies running, unread, and exited sessions per project", () => { const sessions = [ session("running-main", { projectRoot: "/repo" }), diff --git a/lib/project-ordering.ts b/lib/project-ordering.ts index c092ce356..32a1c54d9 100644 --- a/lib/project-ordering.ts +++ b/lib/project-ordering.ts @@ -169,7 +169,14 @@ export function projectActivityCounts( /** Group sessions by logical project identity, or by host-bound physical path. * Every managed project gets a bucket, including empty projects. Physical paths - * compare case-insensitively on Windows; logical IDs stay case-sensitive. */ + * compare case-insensitively on Windows; logical IDs stay case-sensitive. + * Sessions with no workspace key at all are skipped, deliberately: the + * sidebar renders one row per project (it iterates projects, never this + * map's keys), so there is no row a key-less session could appear under — + * an "unknown workspace" bucket here would be unreachable dead data. The + * empty-string fallthrough in workspaceKeyOf already rescues any session + * that carries a key in any field; only a header with no location at all + * is left, and grouping cannot place it under any project. */ export function groupSessionsByProject( projects: ManagedProject[], sessions: SessionInfo[], diff --git a/lib/project-registry.test.mjs b/lib/project-registry.test.mjs index 4bee1b7e3..134d34ad8 100644 --- a/lib/project-registry.test.mjs +++ b/lib/project-registry.test.mjs @@ -93,6 +93,38 @@ test("re-adding a workspace without config preserves its launch config", () => { assert.deepEqual(replaced.projects[0].launchConfig, { advisor: true }); }); +test("re-adding a workspace preserves its alias, sort order, and pin order", () => { + const seeded = parseProjectRegistry(JSON.stringify({ version: 1, projects: [{ + path: P("/one"), addedAt: "2026-01-01T00:00:00.000Z", hidden: false, + alias: "My Workspace", sortOrder: 3, pinOrder: 0, + }] })); + const hidden = hideProject(seeded, P("/one")); + assert.equal(hidden.projects[0].hidden, true); + assert.equal(hidden.projects[0].alias, "My Workspace"); + const revived = upsertProject(hidden, P("/one"), "2026-02-01T00:00:00.000Z"); + const entry = revived.projects[0]; + assert.equal(entry.hidden, false); + assert.equal(entry.alias, "My Workspace"); + assert.equal(entry.sortOrder, 3); + assert.equal(entry.pinOrder, 0); +}); + +test("re-adding a workspace whose pin order was taken moves it last among pins", () => { + // Pinned at 0, hidden; meanwhile another project takes pinOrder 0 (fresh + // pins take max+1 over the visible list, which never counted the hidden + // entry). Re-adding must keep the project pinned — at the end of the + // pinned list — not silently share pinOrder 0 or drop the pin. + const seeded = parseProjectRegistry(JSON.stringify({ version: 1, projects: [ + { path: P("/one"), addedAt: "2026-01-01T00:00:00.000Z", hidden: true, pinOrder: 0 }, + { path: P("/two"), addedAt: "2026-01-02T00:00:00.000Z", hidden: false, pinOrder: 0 }, + ] })); + const revived = upsertProject(seeded, P("/one"), "2026-02-01T00:00:00.000Z"); + const one = revived.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(P("/one"))); + const two = revived.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(P("/two"))); + assert.equal(two.pinOrder, 0); + assert.equal(one.pinOrder, 1); +}); + test("applies batch presentation updates in one pass", () => { const registry = parseProjectRegistry(JSON.stringify({ version: 1, diff --git a/lib/project-registry.ts b/lib/project-registry.ts index 7a850345d..a881e1730 100644 --- a/lib/project-registry.ts +++ b/lib/project-registry.ts @@ -179,10 +179,31 @@ export function upsertProject( const key = comparableProjectPath(canonical); const existing = registry.projects.find((p) => comparableProjectPath(p.path) === key); const projects = registry.projects.filter((p) => comparableProjectPath(p.path) !== key); - // An omitted launchConfig preserves the stored one: re-adding a workspace - // (e.g. un-hiding) without config must not wipe it. Explicit clear goes - // through PATCH with null. - projects.push({ path: canonical, addedAt: now, hidden: false, launchConfig: launchConfig ?? existing?.launchConfig }); + // Re-adding a workspace (e.g. un-hiding) must not wipe its stored display + // data: alias, sort order, pin order, and launch config all carry over + // from the existing entry. An omitted launchConfig preserves the stored + // one; explicit clear goes through PATCH with null. Display fields have no + // POST parameter, so carrying them over is unconditional — PATCH applies + // its own updates on top afterwards. + // Pin-order collision: while this project was hidden, another project may + // have taken its pinOrder (fresh pins take max+1 over the visible list, + // which never counted the hidden entry). Keeping the duplicate would make + // the pinned order ambiguous — orderProjects only stable-sorts ties — so + // a colliding pin moves to the end of the pinned list instead of + // unpinning: the project stays pinned, just last. + let pinOrder = existing?.pinOrder; + if (pinOrder !== undefined && projects.some((p) => !p.hidden && p.pinOrder === pinOrder)) { + pinOrder = Math.max(-1, ...projects.filter((p) => !p.hidden).map((p) => p.pinOrder ?? -1)) + 1; + } + projects.push({ + path: canonical, + addedAt: now, + hidden: false, + alias: existing?.alias, + sortOrder: existing?.sortOrder, + pinOrder, + launchConfig: launchConfig ?? existing?.launchConfig, + }); return { version: 1, projects }; } diff --git a/lib/workspace-memory.test.mjs b/lib/workspace-memory.test.mjs index 7a0be516a..69e01c94d 100644 --- a/lib/workspace-memory.test.mjs +++ b/lib/workspace-memory.test.mjs @@ -2,35 +2,20 @@ import assert from "node:assert/strict"; import test from "node:test"; const { - clearLastOpenSession, - getLastOpenSession, - setLastOpenSession, workspaceKeyOf, } = await import("./workspace-memory.ts"); -function createStorage(values = {}) { - const entries = new Map(Object.entries(values)); - return { - getItem(key) { return entries.get(key) ?? null; }, - setItem(key, value) { entries.set(key, value); }, - removeItem(key) { entries.delete(key); }, - entries, - }; -} - -test("remembers the last session for each project independently", () => { - const storage = createStorage(); - setLastOpenSession("project-a", "session-a", storage); - setLastOpenSession("project-b", "session-b", storage); - - assert.equal(getLastOpenSession("project-a", storage), "session-a"); - assert.equal(getLastOpenSession("project-b", storage), "session-b"); - clearLastOpenSession("project-a", storage); - assert.equal(getLastOpenSession("project-a", storage), null); - assert.equal(getLastOpenSession("project-b", storage), "session-b"); -}); - test("uses the shared project root so worktrees restore the same workspace", () => { assert.equal(workspaceKeyOf({ cwd: "D:/repo-worktrees/feature", projectRoot: "D:/repo" }), "D:/repo"); - assert.equal(workspaceKeyOf({ cwd: "D:/scratch" }), "D:/scratch"); + assert.equal(workspaceKeyOf({ cwd: "/scratch" }), "/scratch"); +}); + +test("empty-string fields fall through to the next workspace key", () => { + // Headers from hand-edited or partially written session files can carry + // "" instead of a missing field; ?? would keep the empty string and the + // session would group under no project. + assert.equal(workspaceKeyOf({ cwd: "/scratch", projectRoot: "", projectKey: "" }), "/scratch"); + assert.equal(workspaceKeyOf({ cwd: "", projectRoot: "/repo", projectKey: "" }), "/repo"); + assert.equal(workspaceKeyOf({ cwd: "", projectRoot: "", projectKey: "" }), ""); + assert.equal(workspaceKeyOf({ cwd: "", projectRoot: "", projectKey: "", poolId: "pool-1", projectId: "proj-1" }), "pool:pool-1:proj-1"); }); diff --git a/lib/workspace-memory.ts b/lib/workspace-memory.ts index e99044633..bf9e5d5ab 100644 --- a/lib/workspace-memory.ts +++ b/lib/workspace-memory.ts @@ -1,63 +1,18 @@ - -const STORAGE_KEY = "omp-web:last-open-by-project"; - -interface StorageLike { - getItem(key: string): string | null; - setItem(key: string, value: string): void; - removeItem(key: string): void; -} - -function browserStorage(): StorageLike | null { - if (typeof window === "undefined") return null; - try { - return window.localStorage; - } catch { - return null; - } -} - -function readEntries(storage: StorageLike): Record { - try { - const raw = storage.getItem(STORAGE_KEY); - if (!raw) return {}; - const value: unknown = JSON.parse(raw); - if (!value || typeof value !== "object" || Array.isArray(value)) return {}; - return Object.fromEntries(Object.entries(value).filter(([, id]) => typeof id === "string" && id.length > 0)) as Record; - } catch { - return {}; - } -} +// NOTE: this module used to also record the last-open session per project +// (get/set/clearLastOpenSession, localStorage key "omp-web:last-open-by-project"). +// No caller ever read the recorded value back — project activation is +// deliberately selection-only (see activateProject in SessionSidebar: it sets +// the selected workspace, it never opens a session) — so the helpers were +// dead writes on every selection and were removed rather than wired into a +// behavior change. Any value already stored under that key is orphaned and +// never read. export function workspaceKeyOf(workspace: { cwd?: string; path?: string; projectRoot?: string; projectKey?: string; poolId?: string; projectId?: string }): string { - if (workspace.poolId && workspace.projectId) return workspace.projectKey ?? `pool:${workspace.poolId}:${workspace.projectId}`; - return workspace.projectKey ?? workspace.projectRoot ?? workspace.cwd ?? workspace.path ?? ""; -} - -export function getLastOpenSession(workspace: string, storage: StorageLike | null = browserStorage()): string | null { - if (!storage) return null; - return readEntries(storage)[workspace] ?? null; -} - -export function setLastOpenSession(workspace: string, sessionId: string, storage: StorageLike | null = browserStorage()): void { - if (!storage) return; - try { - const entries = readEntries(storage); - entries[workspace] = sessionId; - storage.setItem(STORAGE_KEY, JSON.stringify(entries)); - } catch { - // Workspace restoration is a best-effort convenience. - } -} - -export function clearLastOpenSession(workspace: string, storage: StorageLike | null = browserStorage()): void { - if (!storage) return; - try { - const entries = readEntries(storage); - if (!(workspace in entries)) return; - delete entries[workspace]; - if (Object.keys(entries).length === 0) storage.removeItem(STORAGE_KEY); - else storage.setItem(STORAGE_KEY, JSON.stringify(entries)); - } catch { - // Workspace restoration is a best-effort convenience. + if (workspace.poolId && workspace.projectId) { + // Empty strings count as missing, not as a key: hand-edited or partially + // written session headers can carry "" where a field is absent, and ?? + // would keep the empty string, grouping the session under no project. + return workspace.projectKey || `pool:${workspace.poolId}:${workspace.projectId}`; } + return workspace.projectKey || workspace.projectRoot || workspace.cwd || workspace.path || ""; } diff --git a/lib/worktree.test.mjs b/lib/worktree.test.mjs index 0b3f5558d..4d3faf78f 100644 --- a/lib/worktree.test.mjs +++ b/lib/worktree.test.mjs @@ -72,3 +72,43 @@ test("discovers the main checkout and linked worktrees without retaining prunabl rmSync(root, { recursive: true, force: true }); } }); + +test("slash and dash branches with the same sanitized name get distinct worktree dirs", async (t) => { + try { + execFileSync("git", ["--version"], { stdio: "ignore" }); + } catch { + t.skip("git is not installed"); + return; + } + + const root = mkdtempSync(join(tmpdir(), "omp-web-worktree-test-")); + const repo = join(root, "repo"); + const worktreeBase = `${repo}-worktrees`; + try { + git(root, ["init", repo]); + git(repo, ["config", "user.email", "omp-web@example.invalid"]); + git(repo, ["config", "user.name", "omp-web test"]); + writeFileSync(join(repo, "README.md"), "fixture\n"); + git(repo, ["add", "README.md"]); + git(repo, ["commit", "-m", "fixture"]); + + // The pre-existing dir for a-b must keep its name (backwards compat). + const dashed = await addWorktree(repo, "a-b"); + assert.equal(dashed.branch, "a-b"); + assert.ok(dashed.path.endsWith("a-b")); + // a/b sanitizes to the same base name; it must not be refused, and it + // must not reuse the a-b worktree's directory. + const slashed = await addWorktree(repo, "a/b"); + assert.equal(slashed.branch, "a/b"); + assert.notEqual(slashed.path, dashed.path); + assert.equal(existsSync(slashed.path), true); + const worktrees = await listWorktrees(repo); + assert.ok(worktrees.some((entry) => samePath(entry.path, dashed.path) && entry.branch === "a-b")); + assert.ok(worktrees.some((entry) => samePath(entry.path, slashed.path) && entry.branch === "a/b")); + // Re-adding the same branch is still refused with the plain error. + await assert.rejects(() => addWorktree(repo, "a-b"), /Directory already exists/); + } finally { + rmSync(worktreeBase, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/lib/worktree.ts b/lib/worktree.ts index 402895e4c..f257a2b58 100644 --- a/lib/worktree.ts +++ b/lib/worktree.ts @@ -1,4 +1,5 @@ import { execFile } from "child_process"; +import { createHash } from "crypto"; import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "fs"; import { basename, dirname, join, resolve } from "path"; import { promisify } from "util"; @@ -277,6 +278,24 @@ function sanitizeBranchForDir(branch: string): string { return branch.replace(/[\/\\:*?"<>|\s]+/g, "-").replace(/^-+|-+$/g, ""); } +/** Short stable suffix distinguishing branches whose sanitized directory + * names collide (e.g. "a/b" and "a-b" both sanitize to "a-b"). Only used on + * collision, so already-created worktree directories keep their names. */ +function worktreeDirSuffix(branch: string): string { + return createHash("sha256").update(branch).digest("hex").slice(0, 8); +} + +/** Branch checked out at a worktree path, or null when the path is not a + * registered worktree (stray directory, prunable entry, or missing git). */ +async function findWorktreeBranch(cwd: string, worktreePath: string): Promise { + try { + const worktrees = await listWorktrees(cwd); + return findWorktreeByPath(worktrees, worktreePath)?.branch ?? null; + } catch { + return null; + } +} + export async function addWorktree(cwd: string, branch: string): Promise<{ path: string; branch: string }> { const trimmed = branch.trim(); if (!trimmed) throw new Error("Branch name is required"); @@ -294,9 +313,31 @@ export async function addWorktree(cwd: string, branch: string): Promise<{ path: const repoRoot = await getRepoRoot(cwd); const baseDir = `${resolve(repoRoot)}-worktrees`; - const worktreePath = join(baseDir, dirName); + // sanitizeBranchForDir is not injective ("a/b" and "a-b" both map to + // "a-b"), so a plain exists check refuses the second branch. The base name + // is kept as-is so already-created worktrees keep working; only on a real + // collision does the directory gain a short hash of the branch name. + let worktreePath = join(baseDir, dirName); if (existsSync(worktreePath)) { - throw new Error(`Directory already exists: ${worktreePath}`); + const owner = await findWorktreeBranch(cwd, worktreePath); + if (owner === trimmed) { + throw new Error(`Directory already exists: ${worktreePath}`); + } + const disambiguated = join(baseDir, `${dirName}-${worktreeDirSuffix(trimmed)}`); + if (existsSync(disambiguated)) { + const disambiguatedOwner = await findWorktreeBranch(cwd, disambiguated); + if (disambiguatedOwner === trimmed) { + throw new Error(`Directory already exists: ${disambiguated}`); + } + // Distinct error: the directory is taken by something other than this + // branch and even the hash-suffixed fallback is occupied, so no safe + // directory can be picked automatically. + throw new Error( + `Worktree directory already exists for a different branch: ${disambiguated}` + + (disambiguatedOwner ? ` (checked out branch: ${disambiguatedOwner})` : " (not a registered worktree)"), + ); + } + worktreePath = disambiguated; } mkdirSync(baseDir, { recursive: true }); if (lstatSync(baseDir).isSymbolicLink() || !samePath(realPathOrSelf(baseDir), baseDir)) throw new Error("Worktree directory must not be a symbolic link");