Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/api/projects/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export async function POST(req: Request) {
allowFileRoot(projectRoot);

const entry = next.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(projectRoot))!;
return NextResponse.json({ project: { path: entry.path, addedAt: entry.addedAt, launchConfig: entry.launchConfig } satisfies ManagedProject });
return NextResponse.json({ project: { path: entry.path, addedAt: entry.addedAt, alias: entry.alias, sortOrder: entry.sortOrder, pinOrder: entry.pinOrder, launchConfig: entry.launchConfig } satisfies ManagedProject });
} catch (error) {
if (error instanceof ProjectPathError) {
return NextResponse.json({ error: error.message, code: error.code }, { status: 400 });
Expand Down
11 changes: 2 additions & 9 deletions components/SessionSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 { groupSessionsByProject, nextPinOrder, orderProjects, projectActivityCounts, type ProjectSortMode } from "@/lib/project-ordering";
import { comparableProjectPath } from "@/lib/comparable-path";
import { compileSearchQuery, FIRST_MESSAGE_WEIGHT, scoreSearchFields, searchField, TITLE_WEIGHT } from "@/lib/session-search";
Expand Down Expand Up @@ -1288,16 +1288,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(workspaceKeyOf(deleted));
onSessionDeleted?.(id);
loadSessions();
}, [allSessions, onSessionDeleted, loadSessions]);

useEffect(() => {
const selected = allSessions.find((session) => session.id === selectedSessionId);
if (selected) setLastOpenSession(workspaceKeyOf(selected), selected.id);
}, [allSessions, selectedSessionId]);
}, [onSessionDeleted, loadSessions]);

return (
<div className="sidebar-shell" style={{ display: "flex", flexDirection: "column", height: "100%", overflow: "hidden", paddingBottom: "env(safe-area-inset-bottom)" }}>
Expand Down
14 changes: 14 additions & 0 deletions lib/project-ordering.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,20 @@ test("groups sessions under their project, including worktree sessions", () => {
assert.deepEqual(grouped.get("/other").map((s) => s.id).sort(), ["fork", "parent"]);
});

test("session with empty cwd is kept in the unknown-workspace bucket, not dropped", () => {
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"]);
// A header with no cwd at all has no project to group under; it must still
// appear in the grouping (unknown-workspace bucket) instead of vanishing.
const shown = [...grouped.values()].flat().map((s) => s.id);
assert.ok(shown.includes("s1"), "cwd-less session must not vanish from the sidebar grouping");
});

test("projectActivityCounts tallies running, unread, and exited sessions per project", () => {
const sessions = [
session("running-main", { projectRoot: "/repo" }),
Expand Down
16 changes: 14 additions & 2 deletions lib/project-ordering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,10 @@ export function projectActivityCounts(
* matched through a case-folded lookup (Windows/NTFS is case-insensitive and
* session-file cwds can carry different casing than the registered path), so
* casing-only differences land in the right bucket instead of silently
* dropping the session from the sidebar. */
* dropping the session from the sidebar. Sessions with no workspace key at
* all (a header with no cwd) land in an "unknown workspace" bucket keyed ""
* instead of being skipped, so grouping callers can surface them rather
* than losing them. */
export function groupSessionsByProject(
projects: ManagedProject[],
sessions: SessionInfo[],
Expand All @@ -121,9 +124,18 @@ export function groupSessionsByProject(
grouped.set(project.path, bucket);
bucketByKey.set(comparableProjectPath(project.path), bucket);
}
// Lazily created so projects-only callers see no extra entry.
let unknownBucket: SessionInfo[] | null = null;
for (const session of sessions) {
const key = workspaceKeyOf(session);
if (!key) continue;
if (!key) {
if (!unknownBucket) {
unknownBucket = [];
grouped.set("", unknownBucket);
}
unknownBucket.push(session);
continue;
}
// workspaceKeyOf already prefers projectKey, so this IS the session's
// key; bucketByKey covers every registered project under its case-folded
// path, and an exact-case fallback here could only hit when the folded
Expand Down
16 changes: 16 additions & 0 deletions lib/project-registry.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,22 @@ 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("applies batch presentation updates in one pass", () => {
const registry = parseProjectRegistry(JSON.stringify({
version: 1,
Expand Down
19 changes: 15 additions & 4 deletions lib/project-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,21 @@ 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.
projects.push({
path: canonical,
addedAt: now,
hidden: false,
alias: existing?.alias,
sortOrder: existing?.sortOrder,
pinOrder: existing?.pinOrder,
launchConfig: launchConfig ?? existing?.launchConfig,
});
return { version: 1, projects };
}

Expand Down
34 changes: 9 additions & 25 deletions lib/workspace-memory.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,19 @@ import { createJiti } from "jiti";

const jiti = createJiti(import.meta.url, { tsconfigPaths: true });
const {
clearLastOpenSession,
getLastOpenSession,
setLastOpenSession,
workspaceKeyOf,
} = await jiti.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");
});

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: "" }), "");
});
68 changes: 10 additions & 58 deletions lib/workspace-memory.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,15 @@
import type { SessionInfo } from "./types";

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<string, string> {
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<string, string>;
} 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 "without opening a session" (see activateProject in
// SessionSidebar) — so the helpers were dead writes on every selection and
// were removed rather than wired into a behavior change.

export function workspaceKeyOf(session: Pick<SessionInfo, "cwd" | "projectRoot" | "projectKey">): string {
return session.projectKey ?? session.projectRoot ?? session.cwd;
}

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.
}
// 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 session.projectKey || session.projectRoot || session.cwd || "";
}
40 changes: 40 additions & 0 deletions lib/worktree.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,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 });
}
});
45 changes: 43 additions & 2 deletions lib/worktree.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { execFile } from "child_process";
import { createHash } from "crypto";
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "fs";
import { basename, dirname, join, resolve } from "path";
import { promisify } from "util";
Expand Down Expand Up @@ -278,6 +279,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<string | null> {
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");
Expand All @@ -295,9 +314,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 });

Expand Down
Loading