feat: configurable project grouping (#2055)

Co-authored-by: tlh38 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-04-16 16:29:25 -07:00
1 parent 7a08fcf2e8
commit 188a40c315
21 files changed
+1594 -347

No files matched your search

@@ -52,6 +52,10 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
},
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
+58 -27
View File
@@ -160,6 +160,35 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
const normalizedItems: ContextMenuItem[] = [];
for (const sourceItem of source) {
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
};
if (sourceItem.children) {
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
if (normalizedChildren.length === 0) {
continue;
}
normalizedItem.children = normalizedChildren;
}
normalizedItems.push(normalizedItem);
}
return normalizedItems;
}
type WindowTitleBarOptions = Pick<
BrowserWindowConstructorOptions,
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
@@ -1715,14 +1744,7 @@ function registerIpcHandlers(): void {
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
const normalizedItems = normalizeContextMenuItems(items);
if (normalizedItems.length === 0) {
return null;
}
@@ -1743,28 +1765,37 @@ function registerIpcHandlers(): void {
if (!window) return null;
return new Promise<string | null>((resolve) => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
const buildTemplate = (
entries: readonly ContextMenuItem[],
): MenuItemConstructorOptions[] => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
};
if (item.children && item.children.length > 0) {
itemOption.submenu = buildTemplate(item.children);
} else {
itemOption.click = () => resolve(item.id);
}
if (item.destructive && (!item.children || item.children.length === 0)) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
template.push(itemOption);
}
return template;
};
const menu = Menu.buildFromTemplate(template);
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
menu.popup({
window,
...popupPosition,
@@ -1,3 +1,5 @@
import { realpathSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, FileSystem, Layer } from "effect";
@@ -10,6 +12,10 @@ import {
RepositoryIdentityResolverLive,
} from "./RepositoryIdentityResolver.ts";
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
const normalizeResolvedPath = (value: string) =>
normalizePathSeparators(realpathSync.native(value));
const git = (cwd: string, args: ReadonlyArray<string>) =>
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
@@ -41,6 +47,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
expect(identity?.displayName).toBe("t3tools/t3code");
expect(identity?.provider).toBe("github");
expect(identity?.owner).toBe("t3tools");
@@ -48,6 +55,27 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-repository-identity-nested-root-test-",
});
const nestedWorkspace = `${repoRoot}/packages/web`;
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
yield* git(repoRoot, ["init"]);
yield* git(repoRoot, ["remote", "add", "origin", "[email protected]:T3Tools/t3code.git"]);
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(nestedWorkspace);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
it.effect("returns null for non-git folders and repos without remotes", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -42,6 +42,7 @@ function pickPrimaryRemote(
function buildRepositoryIdentity(input: {
readonly remoteName: string;
readonly remoteUrl: string;
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
@@ -57,6 +58,7 @@ function buildRepositoryIdentity(input: {
remoteName: input.remoteName,
remoteUrl: input.remoteUrl,
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(owner ? { owner } : {}),
@@ -108,7 +110,7 @@ async function resolveRepositoryIdentityFromCacheKey(
}
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
return remote ? buildRepositoryIdentity(remote) : null;
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
} catch {
return null;
}
@@ -351,7 +351,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("defaults Claude Opus 4.7 sessions to xhigh effort", () => {
it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -366,14 +366,14 @@ describe("ClaudeAdapterLive", () => {
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "xhigh");
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("forwards xhigh effort for Claude Opus 4.7", () => {
it.effect("maps xhigh effort for Claude Opus 4.7 to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -391,7 +391,7 @@ describe("ClaudeAdapterLive", () => {
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "xhigh");
assert.equal(createInput?.options.effort, "max");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -84,6 +84,7 @@ type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
"command_output" | "file_change_output"
>;
type ClaudeSdkEffort = NonNullable<ClaudeQueryOptions["effort"]>;
type PromptQueueItem =
| {
@@ -217,11 +218,17 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
function getEffectiveClaudeAgentEffort(
effort: ClaudeAgentEffort | null | undefined,
): Exclude<ClaudeAgentEffort, "ultrathink"> | null {
): ClaudeSdkEffort | null {
if (!effort) {
return null;
}
return effort === "ultrathink" ? null : effort;
if (effort === "ultrathink") {
return null;
}
if (effort === "xhigh") {
return "max";
}
return effort;
}
function isClaudeInterruptedMessage(message: string): boolean {
+18 -11
View File
@@ -17,12 +17,7 @@ import {
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
} from "@t3tools/contracts";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
@@ -52,6 +47,7 @@ import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
@@ -78,7 +74,18 @@ const THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, THREAD_ID);
const THREAD_KEY = scopedThreadKey(THREAD_REF);
const UUID_ROUTE_RE = /^\/draft\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_DRAFT_KEY = `${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`;
const PROJECT_KEY = scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID));
const PROJECT_LOGICAL_KEY = deriveLogicalProjectKeyFromSettings(
{
environmentId: LOCAL_ENVIRONMENT_ID,
id: PROJECT_ID,
cwd: "/repo/project",
repositoryIdentity: null,
},
{
sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingOverrides,
},
);
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
@@ -1638,12 +1645,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
customWsRpcResolver = null;
document.body.innerHTML = "";
});
it("re-expands the bootstrap project using its scoped key", async () => {
it("re-expands the bootstrap project using its logical key", async () => {
useUiStateStore.setState({
projectExpandedById: {
[PROJECT_KEY]: false,
[PROJECT_LOGICAL_KEY]: false,
},
projectOrder: [PROJECT_KEY],
projectOrder: [PROJECT_LOGICAL_KEY],
threadLastVisitedAtById: {},
});
@@ -1658,7 +1665,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
await vi.waitFor(
() => {
expect(useUiStateStore.getState().projectExpandedById[PROJECT_KEY]).toBe(true);
expect(useUiStateStore.getState().projectExpandedById[PROJECT_LOGICAL_KEY]).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
+15 -4
View File
@@ -113,7 +113,7 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelection } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import { deriveLogicalProjectKey } from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
@@ -847,10 +847,16 @@ export default function ChatView(props: ChatViewProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const logicalProjectEnvironments = useMemo(() => {
if (!activeProject) return [];
const logicalKey = deriveLogicalProjectKey(activeProject);
const memberProjects = allProjects.filter((p) => deriveLogicalProjectKey(p) === logicalKey);
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
const memberProjects = allProjects.filter(
(p) => deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) === logicalKey,
);
const seen = new Set<string>();
const envs: Array<{
environmentId: EnvironmentId;
@@ -886,6 +892,7 @@ export default function ChatView(props: ChatViewProps) {
}, [
activeProject,
allProjects,
projectGroupingSettings,
primaryEnvironmentId,
savedEnvironmentRegistry,
savedEnvironmentRuntimeById,
@@ -915,7 +922,10 @@ export default function ChatView(props: ChatViewProps) {
throw new Error("No active project is available for this pull request.");
}
const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id);
const logicalProjectKey = deriveLogicalProjectKey(activeProject);
const logicalProjectKey = deriveLogicalProjectKeyFromSettings(
activeProject,
projectGroupingSettings,
);
const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);
if (storedDraftSession) {
setDraftThreadContext(storedDraftSession.draftId, input);
@@ -976,6 +986,7 @@ export default function ChatView(props: ChatViewProps) {
getDraftSessionByLogicalProjectKey,
isServerThread,
navigate,
projectGroupingSettings,
routeKind,
setDraftThreadContext,
setLogicalProjectDraftThreadId,
File diff suppressed because it is too large. Load diff
+221
View File
@@ -0,0 +1,221 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { showContextMenuFallback } from "./contextMenuFallback";
type FakeListener = (event: FakeDomEvent) => void;
class FakeDomEvent {
defaultPrevented = false;
constructor(
readonly type: string,
init: Record<string, unknown> = {},
) {
Object.assign(this, init);
}
preventDefault() {
this.defaultPrevented = true;
}
}
class FakeElement {
children: FakeElement[] = [];
parent: FakeElement | null = null;
style: Record<string, string> & { cssText?: string } = {};
dataset: Record<string, string> = {};
className = "";
disabled = false;
type = "";
private textValue = "";
private readonly listeners = new Map<string, FakeListener[]>();
constructor(readonly tagName: string) {}
appendChild(child: FakeElement) {
child.parent = this;
this.children.push(child);
return child;
}
remove() {
if (!this.parent) {
return;
}
const index = this.parent.children.indexOf(this);
if (index >= 0) {
this.parent.children.splice(index, 1);
}
this.parent = null;
}
addEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type) ?? [];
existing.push(listener);
this.listeners.set(type, existing);
}
dispatchEvent(event: FakeDomEvent) {
for (const listener of this.listeners.get(event.type) ?? []) {
listener(event);
}
return true;
}
set textContent(value: string) {
this.textValue = value;
}
get textContent() {
return `${this.textValue}${this.children.map((child) => child.textContent).join("")}`;
}
querySelectorAll(tagName: string): FakeElement[] {
const matches: FakeElement[] = [];
if (this.tagName === tagName) {
matches.push(this);
}
for (const child of this.children) {
matches.push(...child.querySelectorAll(tagName));
}
return matches;
}
getBoundingClientRect() {
const left = Number.parseInt(this.style.left ?? "0", 10) || 0;
const top = Number.parseInt(this.style.top ?? "0", 10) || 0;
const width = this.tagName === "div" ? 180 : 140;
const height = this.tagName === "div" ? 120 : 28;
return {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
};
}
}
class FakeBody extends FakeElement {
private html = "";
constructor() {
super("body");
}
set innerHTML(value: string) {
this.html = value;
this.children = [];
}
get innerHTML() {
return this.html;
}
}
class FakeDocument {
body = new FakeBody();
private readonly listeners = new Map<string, FakeListener[]>();
createElement(tagName: string) {
return new FakeElement(tagName);
}
addEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type) ?? [];
existing.push(listener);
this.listeners.set(type, existing);
}
removeEventListener(type: string, listener: FakeListener) {
const existing = this.listeners.get(type);
if (!existing) {
return;
}
const index = existing.indexOf(listener);
if (index >= 0) {
existing.splice(index, 1);
}
}
querySelectorAll(tagName: string) {
return this.body.querySelectorAll(tagName);
}
}
function findButton(label: string): FakeElement | undefined {
return (document as unknown as FakeDocument)
.querySelectorAll("button")
.find((button) => button.textContent.includes(label));
}
beforeEach(() => {
vi.stubGlobal("document", new FakeDocument());
vi.stubGlobal("window", {
innerWidth: 1280,
innerHeight: 800,
});
vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
callback(0);
return 0;
});
vi.stubGlobal(
"MouseEvent",
class extends FakeDomEvent {
constructor(type: string, init: Record<string, unknown> = {}) {
super(type, init);
}
},
);
vi.stubGlobal(
"KeyboardEvent",
class extends FakeDomEvent {
constructor(type: string, init: Record<string, unknown> = {}) {
super(type, init);
}
},
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("showContextMenuFallback", () => {
it("resolves a clicked flat menu item", async () => {
const selectionPromise = showContextMenuFallback([
{ id: "rename", label: "Rename" },
{ id: "delete", label: "Delete", destructive: true },
]);
const renameButton = findButton("Rename");
expect(renameButton).toBeTruthy();
renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await expect(selectionPromise).resolves.toBe("rename");
});
it("opens nested submenus and resolves the clicked leaf id", async () => {
const selectionPromise = showContextMenuFallback([
{
id: "rename:submenu",
label: "Rename project",
children: [
{ id: "rename:project-a", label: "/tmp/project-a" },
{ id: "rename:project-b", label: "/tmp/project-b" },
],
},
]);
const parentButton = findButton("Rename project");
expect(parentButton).toBeTruthy();
parentButton?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
const childButton = findButton("/tmp/project-b");
expect(childButton).toBeTruthy();
childButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await expect(selectionPromise).resolves.toBe("rename:project-b");
});
});
+116 -48
View File
@@ -1,9 +1,22 @@
import type { ContextMenuItem } from "@t3tools/contracts";
function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
const rect = menu.getBoundingClientRect();
const left = Math.min(
Math.max(4, preferredLeft),
Math.max(4, window.innerWidth - rect.width - 4),
);
const top = Math.min(
Math.max(4, preferredTop),
Math.max(4, window.innerHeight - rect.height - 4),
);
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
}
/**
* Imperative DOM-based context menu for non-Electron environments.
* Shows a positioned dropdown and returns a promise that resolves
* with the clicked item id, or null if dismissed.
* Supports nested submenus and resolves with the clicked leaf item id.
*/
export function showContextMenuFallback<T extends string>(
items: readonly ContextMenuItem<T>[],
@@ -13,62 +26,117 @@ export function showContextMenuFallback<T extends string>(
const overlay = document.createElement("div");
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[140px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
const menuStack: HTMLDivElement[] = [];
const x = position?.x ?? 0;
const y = position?.y ?? 0;
menu.style.top = `${y}px`;
menu.style.left = `${x}px`;
function cleanup(result: T | null) {
const cleanup = (result: T | null) => {
document.removeEventListener("keydown", onKeyDown);
overlay.remove();
menu.remove();
for (const menu of menuStack) {
menu.remove();
}
resolve(result);
}
};
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
e.preventDefault();
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
cleanup(null);
}
}
};
const closeMenusFromLevel = (level: number) => {
while (menuStack.length > level) {
menuStack.pop()?.remove();
}
};
const openMenu = (
entries: readonly ContextMenuItem<T>[],
preferredLeft: number,
preferredTop: number,
level: number,
) => {
closeMenusFromLevel(level);
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[160px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
menu.style.left = `${preferredLeft}px`;
menu.style.top = `${preferredTop}px`;
menu.dataset.level = String(level);
for (const item of entries) {
const button = document.createElement("button");
button.type = "button";
const hasChildren = Array.isArray(item.children) && item.children.length > 0;
const isLeafDestructive =
!hasChildren && (item.destructive === true || item.id === ("delete" as T));
const isDisabled = item.disabled === true;
button.disabled = isDisabled;
button.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isLeafDestructive
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
const label = document.createElement("span");
label.className = "min-w-0 flex-1 truncate";
label.textContent = item.label;
button.appendChild(label);
if (hasChildren) {
const chevron = document.createElement("span");
chevron.className = "shrink-0 text-muted-foreground/70";
chevron.textContent = "›";
button.appendChild(chevron);
}
if (!isDisabled) {
if (hasChildren) {
button.addEventListener("mouseenter", () => {
const rect = button.getBoundingClientRect();
const nextLeft = rect.right + 4;
const nextTop = rect.top;
openMenu(item.children!, nextLeft, nextTop, level + 1);
const childMenu = menuStack[level + 1];
if (!childMenu) {
return;
}
const childRect = childMenu.getBoundingClientRect();
if (childRect.right > window.innerWidth) {
clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
}
});
button.addEventListener("click", (event) => {
event.preventDefault();
});
} else {
button.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
button.addEventListener("click", () => cleanup(item.id));
}
}
menu.appendChild(button);
}
menu.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
document.body.appendChild(menu);
menuStack[level] = menu;
requestAnimationFrame(() => {
clampMenuPosition(menu, preferredLeft, preferredTop);
});
};
overlay.addEventListener("mousedown", () => cleanup(null));
document.addEventListener("keydown", onKeyDown);
for (const item of items) {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
const isDestructiveAction = item.destructive === true || item.id === "delete";
const isDisabled = item.disabled === true;
btn.disabled = isDisabled;
btn.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isDestructiveAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
if (!isDisabled) {
btn.addEventListener("click", () => cleanup(item.id));
}
menu.appendChild(btn);
}
document.body.appendChild(overlay);
document.body.appendChild(menu);
// Adjust if menu overflows viewport
requestAnimationFrame(() => {
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) {
menu.style.left = `${window.innerWidth - rect.width - 4}px`;
}
if (rect.bottom > window.innerHeight) {
menu.style.top = `${window.innerHeight - rect.height - 4}px`;
}
});
openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
});
}
+165 -4
View File
@@ -10,7 +10,12 @@ import {
type AppState,
type EnvironmentState,
} from "./store";
import { deriveLogicalProjectKey } from "./logicalProject";
import {
deriveLogicalProjectKey,
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
resolveProjectGroupingMode,
} from "./logicalProject";
import type { Project, SidebarThreadSummary } from "./types";
import { DEFAULT_INTERACTION_MODE } from "./types";
@@ -31,6 +36,10 @@ const threadL1 = ThreadId.make("thread-local-only-1");
const threadRO1 = ThreadId.make("thread-remote-only-1");
const SHARED_REPO_CANONICAL_KEY = "github.com/example/shared-repo";
const DEFAULT_GROUPING_SETTINGS = {
sidebarProjectGroupingMode: "repository" as const,
sidebarProjectGroupingOverrides: {},
};
// ── Factory Helpers ──────────────────────────────────────────────────
@@ -238,9 +247,7 @@ describe("environment grouping", () => {
environmentId: primaryEnvId,
name: "local-only",
});
const key = deriveLogicalProjectKey(project);
expect(key).toContain(primaryEnvId);
expect(key).toContain(localOnlyProjectId);
expect(deriveLogicalProjectKey(project)).toBe(derivePhysicalProjectKey(project));
});
it("groups projects from different environments that share the same canonical key", () => {
@@ -273,6 +280,134 @@ describe("environment grouping", () => {
expect(deriveLogicalProjectKey(primary)).toBe(deriveLogicalProjectKey(remote));
});
it("groups repo root and nested projects from the same repository by default", () => {
const rootProject = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
cwd: "/workspace/repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const nestedProject = makeProject({
id: localOnlyProjectId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(deriveLogicalProjectKey(rootProject)).toBe(SHARED_REPO_CANONICAL_KEY);
expect(deriveLogicalProjectKey(nestedProject)).toBe(SHARED_REPO_CANONICAL_KEY);
});
it("uses repository path grouping when requested", () => {
const rootProject = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
cwd: "/workspace/repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const nestedProject = makeProject({
id: localOnlyProjectId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(
deriveLogicalProjectKey(rootProject, {
groupingMode: "repository_path",
}),
).toBe(SHARED_REPO_CANONICAL_KEY);
expect(
deriveLogicalProjectKey(nestedProject, {
groupingMode: "repository_path",
}),
).toBe(`${SHARED_REPO_CANONICAL_KEY}::apps/web`);
});
it("groups matching nested project paths across environments when repo roots differ", () => {
const primary = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "web",
cwd: "/workspace/repo/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/workspace/repo",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
const remote = makeProject({
id: sharedProjectRemoteId,
environmentId: remoteEnvId,
name: "web",
cwd: "/srv/checkout/apps/web",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
rootPath: "/srv/checkout",
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(
deriveLogicalProjectKey(primary, {
groupingMode: "repository_path",
}),
).toBe(`${SHARED_REPO_CANONICAL_KEY}::apps/web`);
expect(
deriveLogicalProjectKey(primary, {
groupingMode: "repository_path",
}),
).toBe(
deriveLogicalProjectKey(remote, {
groupingMode: "repository_path",
}),
);
});
it("does NOT group projects without shared canonical key", () => {
const local = makeProject({
id: localOnlyProjectId,
@@ -286,6 +421,32 @@ describe("environment grouping", () => {
});
expect(deriveLogicalProjectKey(local)).not.toBe(deriveLogicalProjectKey(remote));
});
it("uses per-project overrides from settings", () => {
const project = makeProject({
id: sharedProjectPrimaryId,
environmentId: primaryEnvId,
name: "shared-repo",
repositoryIdentity: {
canonicalKey: SHARED_REPO_CANONICAL_KEY,
locator: {
source: "git-remote",
remoteName: "origin",
remoteUrl: "https://github.com/example/shared-repo.git",
},
},
});
expect(resolveProjectGroupingMode(project, DEFAULT_GROUPING_SETTINGS)).toBe("repository");
expect(
deriveLogicalProjectKeyFromSettings(project, {
...DEFAULT_GROUPING_SETTINGS,
sidebarProjectGroupingOverrides: {
[derivePhysicalProjectKey(project)]: "separate",
},
}),
).toBe(derivePhysicalProjectKey(project));
});
});
describe("selectProjectsAcrossEnvironments", () => {
+3 -4
View File
@@ -13,9 +13,7 @@ import { Throttler } from "@tanstack/react-pacer";
import {
createKnownEnvironment,
getKnownEnvironmentWsBaseUrl,
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
@@ -62,6 +60,7 @@ import { useTerminalStateStore } from "~/terminalStateStore";
import { useUiStateStore } from "~/uiStateStore";
import { WsTransport } from "../../rpc/wsTransport";
import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
import { derivePhysicalProjectKey } from "../../logicalProject";
type EnvironmentServiceState = {
readonly queryClient: QueryClient;
@@ -470,7 +469,7 @@ function syncProjectUiFromStore() {
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
key: derivePhysicalProjectKey(project),
cwd: project.cwd,
})),
);
@@ -543,7 +542,7 @@ function applyRecoveredEventBatch(
const projects = selectProjectsAcrossEnvironments(useStore.getState());
useUiStateStore.getState().syncProjects(
projects.map((project) => ({
key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
key: derivePhysicalProjectKey(project),
cwd: project.cwd,
})),
);
+8 -3
View File
@@ -10,14 +10,19 @@ import {
} from "../composerDraftStore";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { deriveLogicalProjectKey } from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
function useNewThreadState() {
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const router = useRouter();
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
@@ -48,7 +53,7 @@ function useNewThreadState() {
candidate.environmentId === projectRef.environmentId,
);
const logicalProjectKey = project
? deriveLogicalProjectKey(project)
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
: scopedProjectKey(projectRef);
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
@@ -129,7 +134,7 @@ function useNewThreadState() {
});
})();
},
[getCurrentRouteTarget, router, projects],
[getCurrentRouteTarget, projectGroupingSettings, router, projects],
);
}
+25 -34
View File
@@ -528,13 +528,20 @@ describe("wsApi", () => {
});
it("reads and writes persistence through the desktop bridge when available", async () => {
const getClientSettings = vi.fn().mockResolvedValue({
const clientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
sidebarProjectGroupingMode: "repository_path" as const,
sidebarProjectGroupingOverrides: {
"environment-local:/tmp/project": "separate" as const,
},
sidebarProjectSortOrder: "manual" as const,
sidebarThreadSortOrder: "created_at" as const,
timestampFormat: "24-hour" as const,
};
const getClientSettings = vi.fn().mockResolvedValue({
...clientSettings,
});
const setClientSettings = vi.fn().mockResolvedValue(undefined);
const getSavedEnvironmentRegistry = vi.fn().mockResolvedValue([]);
@@ -556,14 +563,7 @@ describe("wsApi", () => {
const api = createLocalApi(rpcClientMock as never);
await api.persistence.getClientSettings();
await api.persistence.setClientSettings({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await api.persistence.setClientSettings(clientSettings);
await api.persistence.getSavedEnvironmentRegistry();
await api.persistence.setSavedEnvironmentRegistry([]);
await api.persistence.getSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
@@ -574,14 +574,7 @@ describe("wsApi", () => {
await api.persistence.removeSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
expect(getClientSettings).toHaveBeenCalledWith();
expect(setClientSettings).toHaveBeenCalledWith({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
expect(setClientSettings).toHaveBeenCalledWith(clientSettings);
expect(getSavedEnvironmentRegistry).toHaveBeenCalledWith();
expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
expect(getSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
@@ -592,15 +585,20 @@ describe("wsApi", () => {
it("falls back to browser storage for persistence when the desktop bridge is missing", async () => {
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await api.persistence.setClientSettings({
const clientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
sidebarProjectGroupingMode: "repository_path" as const,
sidebarProjectGroupingOverrides: {
"environment-local:/tmp/project": "separate" as const,
},
sidebarProjectSortOrder: "manual" as const,
sidebarThreadSortOrder: "created_at" as const,
timestampFormat: "24-hour" as const,
};
await api.persistence.setClientSettings(clientSettings);
await api.persistence.setSavedEnvironmentRegistry([
{
environmentId: EnvironmentId.make("environment-local"),
@@ -616,14 +614,7 @@ describe("wsApi", () => {
"bearer-token",
);
await expect(api.persistence.getClientSettings()).resolves.toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await expect(api.persistence.getClientSettings()).resolves.toEqual(clientSettings);
await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual([
{
environmentId: EnvironmentId.make("environment-local"),
+144 -6
View File
@@ -1,19 +1,157 @@
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
import type { ScopedProjectRef } from "@t3tools/contracts";
import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import { normalizeProjectPathForComparison } from "./lib/projectPaths";
import type { Project } from "./types";
export function deriveLogicalProjectKey(
project: Pick<Project, "environmentId" | "id" | "repositoryIdentity">,
export interface ProjectGroupingSettings {
sidebarProjectGroupingMode: SidebarProjectGroupingMode;
sidebarProjectGroupingOverrides: Record<string, SidebarProjectGroupingMode>;
}
export type ProjectGroupingMode = SidebarProjectGroupingMode;
function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
const seen = new Set<string>();
const unique: string[] = [];
for (const value of values) {
const trimmed = value?.trim();
if (!trimmed || seen.has(trimmed)) {
continue;
}
seen.add(trimmed);
unique.push(trimmed);
}
return unique;
}
function deriveRepositoryRelativeProjectPath(
project: Pick<Project, "cwd" | "repositoryIdentity">,
): string | null {
const rootPath = project.repositoryIdentity?.rootPath?.trim();
if (!rootPath) {
return null;
}
const normalizedProjectPath = normalizeProjectPathForComparison(project.cwd);
const normalizedRootPath = normalizeProjectPathForComparison(rootPath);
if (normalizedProjectPath.length === 0 || normalizedRootPath.length === 0) {
return null;
}
if (normalizedProjectPath === normalizedRootPath) {
return "";
}
const separator = normalizedRootPath.includes("\\") ? "\\" : "/";
const rootPrefix = `${normalizedRootPath}${separator}`;
if (!normalizedProjectPath.startsWith(rootPrefix)) {
return null;
}
return normalizedProjectPath.slice(rootPrefix.length).replaceAll("\\", "/");
}
export function derivePhysicalProjectKeyFromPath(environmentId: string, cwd: string): string {
return `${environmentId}:${normalizeProjectPathForComparison(cwd)}`;
}
export function derivePhysicalProjectKey(project: Pick<Project, "environmentId" | "cwd">): string {
return derivePhysicalProjectKeyFromPath(project.environmentId, project.cwd);
}
export function deriveProjectGroupingOverrideKey(
project: Pick<Project, "environmentId" | "cwd">,
): string {
return derivePhysicalProjectKey(project);
}
export function resolveProjectGroupingMode(
project: Pick<Project, "environmentId" | "cwd">,
settings: ProjectGroupingSettings,
): SidebarProjectGroupingMode {
return (
project.repositoryIdentity?.canonicalKey ??
settings.sidebarProjectGroupingOverrides[deriveProjectGroupingOverrideKey(project)] ??
settings.sidebarProjectGroupingMode
);
}
function deriveRepositoryScopedKey(
project: Pick<Project, "cwd" | "repositoryIdentity">,
groupingMode: SidebarProjectGroupingMode,
): string | null {
const canonicalKey = project.repositoryIdentity?.canonicalKey;
if (!canonicalKey) {
return null;
}
if (groupingMode === "repository") {
return canonicalKey;
}
const relativeProjectPath = deriveRepositoryRelativeProjectPath(project);
if (relativeProjectPath === null) {
return canonicalKey;
}
return relativeProjectPath.length === 0
? canonicalKey
: `${canonicalKey}::${relativeProjectPath}`;
}
export function deriveLogicalProjectKey(
project: Pick<Project, "environmentId" | "id" | "cwd" | "repositoryIdentity">,
options?: {
groupingMode?: SidebarProjectGroupingMode;
},
): string {
const groupingMode = options?.groupingMode ?? "repository";
if (groupingMode === "separate") {
return derivePhysicalProjectKey(project);
}
return (
deriveRepositoryScopedKey(project, groupingMode) ??
derivePhysicalProjectKey(project) ??
scopedProjectKey(scopeProjectRef(project.environmentId, project.id))
);
}
export function deriveLogicalProjectKeyFromSettings(
project: Pick<Project, "environmentId" | "id" | "cwd" | "repositoryIdentity">,
settings: ProjectGroupingSettings,
): string {
return deriveLogicalProjectKey(project, {
groupingMode: resolveProjectGroupingMode(project, settings),
});
}
export function deriveLogicalProjectKeyFromRef(
projectRef: ScopedProjectRef,
project: Pick<Project, "repositoryIdentity"> | null | undefined,
project: Pick<Project, "environmentId" | "id" | "cwd" | "repositoryIdentity"> | null | undefined,
options?: {
groupingMode?: SidebarProjectGroupingMode;
},
): string {
return project?.repositoryIdentity?.canonicalKey ?? scopedProjectKey(projectRef);
return project ? deriveLogicalProjectKey(project, options) : scopedProjectKey(projectRef);
}
export function deriveProjectGroupLabel(input: {
representative: Pick<Project, "name" | "repositoryIdentity">;
members: ReadonlyArray<Pick<Project, "name" | "repositoryIdentity">>;
}): string {
const sharedDisplayNames = uniqueNonEmptyValues(
input.members.map((member) => member.repositoryIdentity?.displayName),
);
if (sharedDisplayNames.length === 1) {
return sharedDisplayNames[0]!;
}
const sharedRepositoryNames = uniqueNonEmptyValues(
input.members.map((member) => member.repositoryIdentity?.name),
);
if (sharedRepositoryNames.length === 1) {
return sharedRepositoryNames[0]!;
}
return input.representative.name;
}
+23 -7
View File
@@ -22,6 +22,11 @@ import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { readLocalApi } from "../localApi";
import { useSettings } from "../hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKeyFromPath,
} from "../logicalProject";
import {
getServerConfigUpdatedNotification,
ServerConfigUpdatedNotification,
@@ -204,6 +209,10 @@ function EventRouter() {
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
@@ -224,14 +233,21 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
useUiStateStore
.getState()
.setProjectExpanded(
scopedProjectKey(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
),
true,
const bootstrapEnvironmentState =
useStore.getState().environmentStateById[payload.environment.environmentId];
const bootstrapProject =
bootstrapEnvironmentState?.projectById[payload.bootstrapProjectId] ?? null;
const bootstrapProjectKey =
(bootstrapProject
? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
: null) ??
(serverConfig?.cwd
? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
: null) ??
scopedProjectKey(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
);
useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
if (readPathname() !== "/") {
return;
+118
View File
@@ -0,0 +1,118 @@
import { scopeProjectRef } from "@t3tools/client-runtime";
import type { EnvironmentId, ScopedProjectRef } from "@t3tools/contracts";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
type ProjectGroupingSettings,
} from "./logicalProject";
import type { Project } from "./types";
export type EnvironmentPresence = "local-only" | "remote-only" | "mixed";
export interface SidebarProjectGroupMember extends Project {
physicalProjectKey: string;
environmentLabel: string | null;
}
export interface SidebarProjectSnapshot extends Project {
projectKey: string;
displayName: string;
groupedProjectCount: number;
environmentPresence: EnvironmentPresence;
memberProjects: readonly SidebarProjectGroupMember[];
memberProjectRefs: readonly ScopedProjectRef[];
remoteEnvironmentLabels: readonly string[];
}
export function buildPhysicalToLogicalProjectKeyMap(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
}): Map<string, string> {
const mapping = new Map<string, string>();
for (const project of input.projects) {
mapping.set(
derivePhysicalProjectKey(project),
deriveLogicalProjectKeyFromSettings(project, input.settings),
);
}
return mapping;
}
export function buildSidebarProjectSnapshots(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
resolveEnvironmentLabel: (environmentId: EnvironmentId) => string | null;
}): SidebarProjectSnapshot[] {
const groupedMembers = new Map<string, SidebarProjectGroupMember[]>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
const member: SidebarProjectGroupMember = {
...project,
physicalProjectKey: derivePhysicalProjectKey(project),
environmentLabel: input.resolveEnvironmentLabel(project.environmentId),
};
const existing = groupedMembers.get(logicalKey);
if (existing) {
existing.push(member);
} else {
groupedMembers.set(logicalKey, [member]);
}
}
const result: SidebarProjectSnapshot[] = [];
const seen = new Set<string>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
if (seen.has(logicalKey)) {
continue;
}
seen.add(logicalKey);
const members = groupedMembers.get(logicalKey) ?? [];
const representative =
(input.primaryEnvironmentId
? members.find((member) => member.environmentId === input.primaryEnvironmentId)
: null) ?? members[0];
if (!representative) {
continue;
}
const hasLocal =
input.primaryEnvironmentId !== null &&
members.some((member) => member.environmentId === input.primaryEnvironmentId);
const hasRemote =
input.primaryEnvironmentId !== null
? members.some((member) => member.environmentId !== input.primaryEnvironmentId)
: false;
const remoteEnvironmentLabels = members
.filter(
(member) =>
input.primaryEnvironmentId !== null &&
member.environmentId !== input.primaryEnvironmentId,
)
.flatMap((member) => (member.environmentLabel ? [member.environmentLabel] : []))
.filter((label, index, labels) => labels.indexOf(label) === index);
result.push({
...representative,
projectKey: logicalKey,
displayName:
members.length > 1
? deriveProjectGroupLabel({
representative,
members,
})
: representative.name,
groupedProjectCount: members.length,
environmentPresence:
hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only",
memberProjects: members,
memberProjectRefs: members.map((member) => scopeProjectRef(member.environmentId, member.id)),
remoteEnvironmentLabels,
});
}
return result;
}
+1
View File
@@ -51,6 +51,7 @@ export type RepositoryIdentityLocator = typeof RepositoryIdentityLocator.Type;
export const RepositoryIdentity = Schema.Struct({
canonicalKey: TrimmedNonEmptyString,
locator: RepositoryIdentityLocator,
rootPath: Schema.optionalKey(TrimmedNonEmptyString),
displayName: Schema.optionalKey(TrimmedNonEmptyString),
provider: Schema.optionalKey(TrimmedNonEmptyString),
owner: Schema.optionalKey(TrimmedNonEmptyString),
+1
View File
@@ -60,6 +60,7 @@ export interface ContextMenuItem<T extends string = string> {
label: string;
destructive?: boolean;
disabled?: boolean;
children?: readonly ContextMenuItem<T>[];
}
export type DesktopUpdateStatus =
+15
View File
@@ -23,10 +23,25 @@ export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
export const SidebarProjectGroupingMode = Schema.Literals([
"repository",
"repository_path",
"separate",
]);
export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;
export const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository";
export const ClientSettingsSchema = Schema.Struct({
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
),
sidebarProjectGroupingOverrides: Schema.Record(
TrimmedNonEmptyString,
SidebarProjectGroupingMode,
).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
),