diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 3d6575bd6a405..800bd27f41582 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -145,6 +145,7 @@ const layerTest = Layer.mergeAll( }), request: () => Effect.void, readRepositoryIdentity: () => Effect.succeed(null), + getAvailableRepositoryIdentity: () => Effect.succeed(null), getAvailable: () => Effect.succeed({ repositoryIdentity: null, diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index fbc610235dd01..e87e295e08ed6 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -695,3 +695,36 @@ describe("skipUnchangedThreadShells", () => { }), ); }); + +describe("shellStreamItemFromEnrichmentRefresh", () => { + it("carries a project whose tracked folder resolved, as well as one whose own root did", () => { + const project = ( + id: string, + workspaceRoot: string, + trackedFolders: ReadonlyArray<{ path: string; name: string }> = [], + ) => ({ + id: ProjectId.make(id), + title: id, + workspaceRoot, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + trackedFolders, + createdAt: "2026-09-01T00:00:00Z", + updatedAt: "2026-09-01T00:00:00Z", + }); + const item = shellStreamItemFromEnrichmentRefresh({ + snapshot: { + ...emptyShellSnapshot, + projects: [ + project("shop", "/work/shop", [{ path: "/work/shop/api", name: "api" }]), + project("api", "/work/shop/api"), + project("other", "/work/other"), + ], + } as OrchestrationV2ShellSnapshot, + changes: [{ workspaceRoot: "/work/shop/api" }], + }); + expect(item.snapshot.projects.map((entry) => entry.id)).toEqual(["shop", "api"]); + expect(item.resolvedRepositoryIdentityRoots).toEqual(["/work/shop/api"]); + }); +}); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 5ee1005b16830..c65f06db0b6a8 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -701,8 +701,12 @@ export function shellStreamItemFromEnrichmentRefresh(input: { kind: "snapshot", snapshot: { ...input.snapshot, - projects: input.snapshot.projects.filter((project) => - resolvedRepositoryIdentityRoots.includes(project.workspaceRoot), + projects: input.snapshot.projects.filter( + (project) => + resolvedRepositoryIdentityRoots.includes(project.workspaceRoot) || + project.trackedFolders?.some((folder) => + resolvedRepositoryIdentityRoots.includes(folder.path), + ) === true, ), threads: [], archivedThreads: [], diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index f4b1c59931c22..d051f37815c8c 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -73,12 +73,16 @@ export const layer = HttpApiBuilder.group( projects, (project) => // Use available enrichment only; git probes can take a minute and exceed shell-snapshot budgets. - projectEnrichment.getAvailable(project.workspaceRoot).pipe( - Effect.map((enrichment) => ({ - ...project, - repositoryIdentity: enrichment.repositoryIdentity, - })), - ), + projectEnrichment + .getAvailable(project.workspaceRoot) + .pipe( + Effect.flatMap((enrichment) => + ProjectEnrichmentService.withTrackedFolderIdentities( + { ...project, repositoryIdentity: enrichment.repositoryIdentity }, + (root) => projectEnrichment.getAvailableRepositoryIdentity(root), + ), + ), + ), { concurrency: 16 }, ), ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 8dcb4f946fb0e..afad32e67a78a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1369,6 +1369,7 @@ const layerSharedApplicationDataPlaneTest = Layer.mergeAll( }), request: () => Effect.void, readRepositoryIdentity: () => Effect.succeed(null), + getAvailableRepositoryIdentity: () => Effect.succeed(null), getAvailable: () => Effect.succeed({ repositoryIdentity: null, diff --git a/apps/server/src/project/ProjectEnrichmentService.test.ts b/apps/server/src/project/ProjectEnrichmentService.test.ts index 1db904c3b4c4d..fb22641a7d4b0 100644 --- a/apps/server/src/project/ProjectEnrichmentService.test.ts +++ b/apps/server/src/project/ProjectEnrichmentService.test.ts @@ -388,3 +388,41 @@ it.effect("keeps a lookup's identity when another root is invalidated mid-flight }).pipe(Effect.provide(layer(layerMetadata))); }), ); + +it.effect("fills in tracked folder identities once they resolve, without asking for favicons", () => + Effect.gen(function* () { + const faviconStarts = yield* Ref.make(0); + const layerMetadata = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => + Effect.succeed(workspaceRoot === "/shop/notes" ? null : identity(workspaceRoot)), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, + resolvePath: () => Ref.update(faviconStarts, (count) => count + 1).pipe(Effect.as(null)), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectEnrichment.ProjectEnrichmentService; + const project = { + trackedFolders: [ + { path: "/shop/api", name: "api" }, + { path: "/shop/notes", name: "notes" }, + ], + }; + const read = ProjectEnrichment.withTrackedFolderIdentities(project, (root) => + service.getAvailableRepositoryIdentity(root), + ); + + assert.deepStrictEqual(yield* read, project); + yield* waitForAvailable(service, "/shop/api", (value) => value.repositoryIdentity !== null); + yield* waitForAvailable(service, "/shop/notes", (value) => value.repositoryIdentityResolved); + assert.deepStrictEqual((yield* read).trackedFolders, [ + { path: "/shop/api", name: "api", repositoryIdentity: identity("/shop/api") }, + { path: "/shop/notes", name: "notes" }, + ]); + assert.equal(yield* Ref.get(faviconStarts), 0); + }).pipe(Effect.provide(layer(layerMetadata))); + }), +); diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.ts index c08bba24bcceb..b08a134a07a73 100644 --- a/apps/server/src/project/ProjectEnrichmentService.ts +++ b/apps/server/src/project/ProjectEnrichmentService.ts @@ -1,4 +1,4 @@ -import type { RepositoryIdentity } from "@t3tools/contracts"; +import type { ProjectTrackedFolder, RepositoryIdentity } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; @@ -50,6 +50,10 @@ export class ProjectEnrichmentService extends Context.Service< readonly readRepositoryIdentity: ( workspaceRoot: string, ) => Effect.Effect; + /** The identity `peek` reports, requesting it when none is cached; favicons are left alone. */ + readonly getAvailableRepositoryIdentity: ( + workspaceRoot: string, + ) => Effect.Effect; readonly invalidate: (workspaceRoots: Iterable) => Effect.Effect; /** Re-resolves past both identity caches and publishes a found identity, leaving the favicon alone. */ readonly refreshRepositoryIdentity: (workspaceRoot: string) => Effect.Effect; @@ -267,6 +271,14 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( }); // peek/request/getAvailable run per project on every shell read, inside the caller's span; own spans were ~0ms noise. + const availableRepositoryIdentity = ( + workspaceRoot: string, + cached: Option.Option>, + ) => + isSuccessfullyResolved(cached) + ? availableValue(cached) + : (lastRepositoryIdentities.get(workspaceRoot) ?? null); + const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fnUntraced( function* (workspaceRoot) { const [repositoryIdentity, faviconPath] = yield* Effect.all( @@ -276,17 +288,23 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( ] as const, { concurrency: "unbounded" }, ); - const repositoryIdentityResolved = isSuccessfullyResolved(repositoryIdentity); return { - repositoryIdentity: repositoryIdentityResolved - ? availableValue(repositoryIdentity) - : (lastRepositoryIdentities.get(workspaceRoot) ?? null), + repositoryIdentity: availableRepositoryIdentity(workspaceRoot, repositoryIdentity), faviconPath: availableValue(faviconPath), - repositoryIdentityResolved, + repositoryIdentityResolved: isSuccessfullyResolved(repositoryIdentity), }; }, ); + const getAvailableRepositoryIdentity: ProjectEnrichmentService["Service"]["getAvailableRepositoryIdentity"] = + Effect.fnUntraced(function* (workspaceRoot) { + const cached = yield* Cache.getSuccess(repositoryIdentityCache, workspaceRoot); + if (!(yield* Cache.has(repositoryIdentityCache, workspaceRoot))) { + yield* requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"); + } + return availableRepositoryIdentity(workspaceRoot, cached); + }); + const request: ProjectEnrichmentService["Service"]["request"] = Effect.fnUntraced( function* (workspaceRoot) { const [hasRepositoryIdentity, hasFaviconPath] = yield* Effect.all( @@ -358,10 +376,31 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( request, getAvailable, readRepositoryIdentity, + getAvailableRepositoryIdentity, invalidate, refreshRepositoryIdentity, subscribeChanges: PubSub.subscribe(changes), }); }); +/** + * A project shell's tracked folders with the repository identities `identityOf` knows. A folder + * whose identity is unknown, or that is not a repository, stays as stored. + */ +export const withTrackedFolderIdentities = < + Project extends { readonly trackedFolders?: ReadonlyArray | undefined }, +>( + project: Project, + identityOf: (workspaceRoot: string) => Effect.Effect, +): Effect.Effect => + project.trackedFolders === undefined || project.trackedFolders.length === 0 + ? Effect.succeed(project) + : Effect.forEach(project.trackedFolders, (folder) => + identityOf(folder.path).pipe( + Effect.map((repositoryIdentity) => + repositoryIdentity === null ? folder : { ...folder, repositoryIdentity }, + ), + ), + ).pipe(Effect.map((trackedFolders) => ({ ...project, trackedFolders }))); + export const layer = Layer.effect(ProjectEnrichmentService, make()); diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 80fabe6101c05..04dc481485ca7 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -781,12 +781,16 @@ export const make = Effect.gen(function* () { ); const enrichShell = (shell: OrchestrationProjectShell) => - projectEnrichment.getAvailable(shell.workspaceRoot).pipe( - Effect.map((enrichment) => ({ - ...shell, - repositoryIdentity: enrichment.repositoryIdentity, - })), - ); + projectEnrichment + .getAvailable(shell.workspaceRoot) + .pipe( + Effect.flatMap((enrichment) => + ProjectEnrichmentService.withTrackedFolderIdentities( + { ...shell, repositoryIdentity: enrichment.repositoryIdentity }, + (root) => projectEnrichment.getAvailableRepositoryIdentity(root), + ), + ), + ); const getShell: ProjectService["Service"]["getShell"] = Effect.fn("ProjectService.getShell")( function* (projectId) { diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b6922b9e90996..829c8fdd58cac 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -898,13 +898,17 @@ const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( projects, (project) => projectEnrichment.getAvailable(project.workspaceRoot).pipe( - Effect.map((enrichment) => ({ - project: { - ...project, - repositoryIdentity: enrichment.repositoryIdentity, - }, - repositoryIdentityResolved: enrichment.repositoryIdentityResolved, - })), + Effect.flatMap((enrichment) => + ProjectEnrichmentService.withTrackedFolderIdentities( + { ...project, repositoryIdentity: enrichment.repositoryIdentity }, + (root) => projectEnrichment.getAvailableRepositoryIdentity(root), + ).pipe( + Effect.map((enriched) => ({ + project: enriched, + repositoryIdentityResolved: enrichment.repositoryIdentityResolved, + })), + ), + ), ), { concurrency: 16 }, ).pipe( @@ -1308,10 +1312,26 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc ]), ); const snapshotSequence = yield* applicationEvents.latestApplicationSequence; - const changedProjects = (yield* projects.listShells()).flatMap((project) => - identities.has(project.workspaceRoot) - ? [{ ...project, repositoryIdentity: identities.get(project.workspaceRoot) ?? null }] - : [], + // Peeks only: requesting here would re-resolve whatever expired on every refresh. + const identityOf = (root: string) => + identities.has(root) + ? Effect.succeed(identities.get(root) ?? null) + : projectEnrichment.peek(root).pipe(Effect.map((known) => known.repositoryIdentity)); + const changedProjects = yield* Effect.forEach( + (yield* projects.listShells()).filter( + (project) => + identities.has(project.workspaceRoot) || + project.trackedFolders?.some((folder) => identities.has(folder.path)) === true, + ), + (project) => + identityOf(project.workspaceRoot).pipe( + Effect.flatMap((repositoryIdentity) => + ProjectEnrichmentService.withTrackedFolderIdentities( + { ...project, repositoryIdentity }, + identityOf, + ), + ), + ), ); return shellStreamItemFromEnrichmentRefresh({ snapshot: { diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1fb930f55fabc..c8b3ea38e8cea 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -14,7 +14,7 @@ import { } from "@t3tools/contracts"; import { isMacPlatform } from "@t3tools/shared/keybindings"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { act, fakeTimers, render } from "../../test/render"; import { openCommandPalette } from "../commandPaletteBus"; @@ -513,3 +513,113 @@ describe("sidebar settled pagination", () => { expect(screen.container.querySelectorAll("[data-thread-item]")).toHaveLength(loadedRows); }); }); + +describe("sidebar multi-repo projects", () => { + // shop covers api's folder; fleet stands alone. Thread 3 shows Input. + function setUp(stack: DisposableStack, gathered: boolean) { + const style = document.createElement("style"); + style.textContent = appCss; + document.head.append(style); + stack.defer(() => style.remove()); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + sidebarGatherProjectThreads: gathered, + }); + const shop = { + ...project("shop"), + trackedFolders: [{ path: "/projects/api", name: "api", discovered: true }], + }; + const api = project("api"); + const fleet = project("fleet"); + vi.mocked(useProjects).mockReturnValue([shop, api, fleet]); + const shell = ( + projectId: ProjectId, + index: number, + overrides: Partial = {}, + ) => ({ ...threadShell(projectId, index), ...overrides }); + vi.mocked(useQuietThreadShells).mockReturnValue([ + shell(api.id, 1), + shell(fleet.id, 2), + shell(shop.id, 3, { hasPendingUserInput: true }), + shell(shop.id, 4), + ]); + vi.mocked(useServerConfigs).mockReset(); + vi.mocked(useThreadRouteTarget).mockReturnValue(null); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: null, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn(), + routeDraftId: null, + routeThreadRef: null, + }); + return render( + + + , + ); + } + + it.each([true, false])( + "folds a covered project's threads into its covering project, gathered=%s", + async (gathered) => { + using stack = new DisposableStack(); + await using screen = await setUp(stack, gathered); + await expect.element(screen.getByText("Thread 4")).toBeInTheDocument(); + await expect.element(screen.getByText("api · shop")).toBeInTheDocument(); + const rows = () => + [ + ...screen.container.querySelectorAll( + '[data-testid="sidebar-gathered-header"], [data-testid="sidebar-row-card"]', + ), + ].map((row) => + row.getAttribute("data-testid") === "sidebar-gathered-header" + ? `# ${row.lastElementChild?.textContent}` + : (row.textContent?.match(/Thread \d/)?.[0] ?? ""), + ); + if (gathered) { + // The status thread leads; shop's threads, api's among them, gather at the first one. + expect(rows()).toEqual(["Thread 3", "# shop", "Thread 1", "Thread 4", "Thread 2"]); + } else { + expect(rows()).toEqual(["Thread 1", "Thread 2", "Thread 3", "Thread 4"]); + } + }, + ); + + it("lists a folded project under the project that covers it, indented like the sidebar", async () => { + using stack = new DisposableStack(); + await using screen = await setUp(stack, true); + await expect.element(screen.getByText("api · shop").first()).toBeInTheDocument(); + const iconX = (element: Element | null | undefined) => + element?.querySelector("[data-slot=project-monogram]")?.getBoundingClientRect().left ?? NaN; + const gatheredCard = [...document.querySelectorAll("[data-testid=sidebar-row-card]")].find( + (card) => card.textContent?.includes("Thread 1"), + ); + const sidebarIndent = + iconX(gatheredCard) - iconX(document.querySelector("[data-testid=sidebar-gathered-header]")); + + const trigger = () => screen.container.querySelector('[aria-label^="Projects"]')!; + await userEvent.click(trigger()); + // The menu opens in a portal outside the rendered sidebar. + const option = (name: string) => page.getByRole("option", { name, exact: true }); + await expect.element(option("api")).toBeVisible(); + const names = [...document.querySelectorAll("[role=option]")].map( + (row) => row.querySelector("span.truncate")?.textContent, + ); + expect(names.indexOf("api")).toBe(names.indexOf("shop") + 1); + const menuIndent = iconX(option("api").element()) - iconX(option("shop").element()); + expect(sidebarIndent).toBeGreaterThan(0); + expect(menuIndent).toBe(sidebarIndent); + + await option("api").click(); + await vi.waitFor(() => expect(trigger().getAttribute("aria-label")).toBe("Projects: api")); + await expect.element(screen.getByText("Thread 1")).toBeInTheDocument(); + await vi.waitFor(() => expect(screen.container.textContent).not.toContain("Thread 4")); + await userEvent.click(trigger()); + await expect.element(option("api")).toHaveAttribute("aria-selected", "true"); + await expect.element(option("shop")).toHaveAttribute("aria-selected", "false"); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index a17427fcdb54e..be32e10eae6be 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -36,7 +36,9 @@ import { type SidebarListMarker, type SidebarSection, resolveSidebarDropVerb, + gatherSidebarThreads, groupSidebarThreadsByProject, + sidebarRowShowsStatus, resolveSidebarFolderDot, sidebarFolderExpansionKeys, withoutRemovedCheckout, @@ -1648,6 +1650,71 @@ describe("sidebarFolderExpansionKeys", () => { }); }); +describe("gatherSidebarThreads", () => { + it("leads with status threads, then gathers each group's threads at its first one", () => { + const shop = ProjectId.make("shop"); + const api = ProjectId.make("api"); + const fleet = ProjectId.make("fleet"); + const thread = (id: string, projectId: ProjectId, status = false) => ({ + id, + environmentId: localEnvironmentId, + projectId, + status, + }); + const group = { + projectKey: "shop", + memberProjectRefs: [ + { environmentId: localEnvironmentId, projectId: shop }, + { environmentId: localEnvironmentId, projectId: api }, + ], + }; + const runs = gatherSidebarThreads( + [group], + [ + thread("fleet-1", fleet), + thread("api-1", api), + thread("shop-done", shop, true), + thread("fleet-2", fleet), + thread("shop-1", shop), + ], + (entry) => !entry.status, + ); + expect( + runs.map((run) => [run.group?.projectKey ?? null, run.threads.map((entry) => entry.id)]), + ).toEqual([ + [null, ["shop-done"]], + [null, ["fleet-1"]], + ["shop", ["api-1", "shop-1"]], + [null, ["fleet-2"]], + ]); + }); +}); + +describe("sidebarRowShowsStatus", () => { + const idle = { + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, + pendingSubagentRequest: null, + interactionMode: "default" as const, + latestRun: null, + runtime: null, + settledOverride: null, + }; + + it("is false for a quiet thread and true once it needs input or woke unseen", () => { + expect(sidebarRowShowsStatus(idle, null)).toBe(false); + expect(sidebarRowShowsStatus({ ...idle, hasPendingUserInput: true }, null)).toBe(true); + expect(sidebarRowShowsStatus(idle, "2026-07-01T00:00:00.000Z")).toBe(true); + expect( + sidebarRowShowsStatus( + { ...idle, lastVisitedAt: "2026-07-02T00:00:00.000Z" }, + "2026-07-01T00:00:00.000Z", + ), + ).toBe(false); + }); +}); + describe("groupSidebarThreadsByProject", () => { it("puts each thread in its project's folder and drops empty projects unless kept", () => { const remoteEnvironmentId = EnvironmentId.make("environment-remote"); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 0771ea2e33d5d..54a1598e46559 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -40,6 +40,7 @@ import { type ThreadSortInput, } from "@t3tools/client-runtime/state/thread-sort"; import type { SidebarThreadSummary, Thread } from "../types"; +import { parseTimestampDate } from "../timestampFormat"; import { normalizeSearchText } from "../lib/utils"; import { isLatestRunSettled } from "../session-logic"; import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement"; @@ -1003,6 +1004,36 @@ export function resolveSidebarRowStatus( return hasUnseenRunFailure(thread) ? status : "ready"; } +/** Woke shows from the wake until the user visits, unless the thread was settled since. */ +export function isSidebarThreadWoke( + thread: Pick & { + readonly lastVisitedAt?: string | null | undefined; + }, + wokeAt: string | null, +): boolean { + const wokeAtDate = wokeAt === null ? null : parseTimestampDate(wokeAt); + const visitedDate = thread.lastVisitedAt ? parseTimestampDate(thread.lastVisitedAt) : null; + return ( + wokeAtDate !== null && + (visitedDate === null || visitedDate < wokeAtDate) && + thread.settledOverride !== "settled" + ); +} + +/** Whether a row shows a status such as Working, Input, Done or Woke. */ +export function sidebarRowShowsStatus( + thread: ThreadStatusInput & + SidebarThreadStatusInput & + Pick, + wokeAt: string | null, +): boolean { + return ( + resolveSidebarRowStatus(thread) !== "ready" || + hasUnseenCompletion(thread) || + isSidebarThreadWoke(thread, wokeAt) + ); +} + /** What the window title says the open thread is doing, in the words its announcer uses. */ export function resolveWindowTitleThreadStatus( thread: SidebarThreadStatusInput, @@ -1101,6 +1132,55 @@ export function groupSidebarThreadsByProject< return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group)); } +/** + * The default sidebar's active rows in runs. Threads `gathers` rejects, the ones showing a + * status, lead in their own order. After them, each group's threads gather at the place of its + * first one, and a thread in no group is a run of its own. + */ +export function gatherSidebarThreads< + TGroup extends { + readonly memberProjectRefs: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectId: string; + }>; + }, + TThread extends Pick, +>( + groups: readonly TGroup[], + threads: readonly TThread[], + gathers: (thread: TThread) => boolean, +): Array<{ readonly group: TGroup | null; readonly threads: TThread[] }> { + const groupByProject = new Map(); + for (const group of groups) { + for (const ref of group.memberProjectRefs) { + groupByProject.set(`${ref.environmentId}:${ref.projectId}`, group); + } + } + const leading: Array<{ readonly group: TGroup | null; readonly threads: TThread[] }> = []; + const runs: typeof leading = []; + const runByGroup = new Map(); + for (const thread of threads) { + if (!gathers(thread)) { + leading.push({ group: null, threads: [thread] }); + continue; + } + const group = groupByProject.get(`${thread.environmentId}:${thread.projectId}`); + if (group === undefined) { + runs.push({ group: null, threads: [thread] }); + continue; + } + const run = runByGroup.get(group); + if (run) { + run.threads.push(thread); + continue; + } + const created = { group, threads: [thread] }; + runByGroup.set(group, created); + runs.push(created); + } + return [...leading, ...runs]; +} + export type SidebarV2TopStatusKind = | "approval" | "done" diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2a8dcdff50d86..756ac2faa8b54 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -110,6 +110,7 @@ import { configuredHostedAppUrl } from "../hostedPairing"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; import { SidebarFolderDrop } from "./sidebar/SidebarFolderDrop"; import { + isCoveringProject, pickableProjectGroups, selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; @@ -182,7 +183,10 @@ import { import { applySidebarThreadDrop, filterSidebarV2VisibleThreads, + gatherSidebarThreads, groupSidebarThreadsByProject, + resolveThreadLastVisitedAt, + sidebarRowShowsStatus, sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, @@ -279,6 +283,7 @@ import { useSidebarDrafts, } from "./sidebar/SidebarDraftBlock"; import { + SidebarGatheredHeader, SidebarProjectFolderHeader, sidebarFolderRowId, } from "./sidebar/SidebarProjectFolderHeader"; @@ -339,6 +344,7 @@ const sidebarProviderEntriesAtom = Atom.make((get) => { const EMPTY_PROVIDER_ENTRIES: ReadonlyMap = new Map(); const EMPTY_THREADS: readonly EnvironmentThreadShell[] = []; +const NO_GATHER_GROUPS: readonly SidebarProjectSnapshot[] = []; const EMPTY_DRAFT_IDS: readonly DraftId[] = []; const SETTLED_TAIL_INITIAL_COUNT = 10; @@ -441,6 +447,8 @@ function useSidebarThreads(input: { readonly folderGroups: readonly SidebarProjectSnapshot[] | null; // Keeps folders with no active threads, so a project the user filtered to or pinned can start one. readonly keepEmptyFolders: (group: SidebarProjectSnapshot) => boolean; + // Groups whose active threads that show no status gather under their name; empty turns it off. + readonly gatherGroups: readonly SidebarProjectSnapshot[]; }) { const { projectScopeKey, @@ -454,6 +462,7 @@ function useSidebarThreads(input: { departingThreadKey, folderGroups, keepEmptyFolders: keepEmpty, + gatherGroups, } = input; const shelfRouteThreadKey = routeRowThreadKey === departingThreadKey ? null : routeRowThreadKey; // Folders already separate the work, so boring mode has no Working shelf. @@ -483,6 +492,7 @@ function useSidebarThreads(input: { ); // Shared with the old per-project sidebar, so folders keep their open state. const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); + const localLastVisitedAtById = useUiStateStore((store) => store.threadLastVisitedAtById); const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded); const [settledTail, setSettledTail] = useState({ scopeKey: projectScopeKey, @@ -506,8 +516,43 @@ function useSidebarThreads(input: { clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); - const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } = - partition; + const { pinnedThreads, workingThreads, snoozedThreads, settledThreads } = partition; + // Rows showing a status need the user, so they lead, ahead of the gathered groups. + const gatheredRuns = + folderGroups === null && gatherGroups.length > 0 + ? gatherSidebarThreads( + gatherGroups, + partition.activeThreads, + (thread) => + !sidebarRowShowsStatus( + { + ...thread, + lastVisitedAt: resolveThreadLastVisitedAt( + thread.lastVisitedAt, + localLastVisitedAtById[threadShellKey(thread)], + ), + }, + threadWokeAt(thread, { now: partition.snoozeNow }), + ), + ) + : null; + const activeThreads = gatheredRuns + ? gatheredRuns.flatMap((run) => run.threads) + : partition.activeThreads; + const activeGatheredByThreadKey = new Map< + string, + { readonly group: SidebarProjectSnapshot; readonly first: boolean; readonly last: boolean } + >(); + for (const run of gatheredRuns ?? []) { + if (run.group === null) continue; + for (const [index, thread] of run.threads.entries()) { + activeGatheredByThreadKey.set(threadShellKey(thread), { + group: run.group, + first: index === 0, + last: index === run.threads.length - 1, + }); + } + } // Older settled threads load in pages; the shelf lists them only as far as they are loaded. const olderSettledShelf = useOlderSettledShelf({ scopes: olderSettledScopes([...serverConfigs.keys()], scopedProjectKeys), @@ -581,6 +626,8 @@ function useSidebarThreads(input: { } return { ...partition, + activeThreads, + activeGatheredByThreadKey, threads, workingShelfEnabled, searchableThreads: [ @@ -834,22 +881,39 @@ function useSidebarLookups() { projects.map((project) => [`${project.environmentId}:${project.id}`, project] as const), ); const projectDisplayNameByKey = new Map( - projectGroups.flatMap((group) => - group.memberProjects.map( + projectGroups.flatMap((group) => [ + ...group.memberProjects.map( (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const, ), - ), + // A folded project's threads name the repository they work in, then the group. + ...group.folded.flatMap((folded) => + folded.memberProjectRefs.map( + (ref) => + [ + `${ref.environmentId}:${ref.projectId}`, + `${folded.folderName} · ${group.displayName}`, + ] as const, + ), + ), + ]), ); const projectGroupByScopeKey = new Map( - projectGroups.map((project) => [project.projectKey, project] as const), + projectGroups + .flatMap((project) => [project, ...project.folded]) + .map((project) => [project.projectKey, project] as const), ); + // A folded project stays pickable on its own, indented under the project that covers it. const projectScopeItems = [ - { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: gt("Add project") }, - { value: "all", label: gt("All projects") }, - ...pickableProjectGroups(projectGroups).map((project) => ({ - value: project.projectKey, - label: project.displayName, - })), + { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: gt("Add project"), indented: false }, + { value: "all", label: gt("All projects"), indented: false }, + ...pickableProjectGroups(projectGroups).flatMap((project) => [ + { value: project.projectKey, label: project.displayName, indented: false }, + ...pickableProjectGroups(project.folded).map((folded) => ({ + value: folded.projectKey, + label: folded.displayName, + indented: true, + })), + ]), ]; return { projects, @@ -864,9 +928,15 @@ function useSidebarLookups() { }; } -function ProjectScopeRowIcon(props: { isSelected: boolean; children: ReactNode }) { +function ProjectScopeRowIcon(props: { + isSelected: boolean; + indented: boolean; + children: ReactNode; +}) { return ( - + {props.children} {props.isSelected ? ( @@ -1000,6 +1070,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, }); const boringSidebarEnabled = useClientSettings((settings) => settings.boringSidebarEnabled); + const gatherProjectThreads = useClientSettings( + (settings) => settings.sidebarGatherProjectThreads, + ); const folderRowsMultiline = useClientSettings((settings) => settings.boringSidebarMultilineRows); const newThreadContext = useHandleNewThread(); // Row callbacks capture only the handler; the rest of the context changes with the route. @@ -1097,16 +1170,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // loaded. The stored keys are left alone, so the scope returns with its project. // An archived project's scope reads as all projects, matching the menu. const scopeGroups = pickableProjectGroups(projectGroups); + const allScopeGroups = projectGroups.flatMap((project) => [project, ...project.folded]); const archivedProjectKeys = new Set( - projectGroups.filter((project) => project.archived).map((project) => project.projectKey), + allScopeGroups.filter((project) => project.archived).map((project) => project.projectKey), ); const chosenProjectScopeKeys = resolveSidebarProjectScopeKeys({ - groups: projectGroups, + groups: allScopeGroups, keys: persistedProjectScopeKeys, settings: projectGroupingSettings, canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady, }).filter((key) => !archivedProjectKeys.has(key)); - const chosenProjectGroups = scopeGroups.filter((project) => + const chosenProjectGroups = pickableProjectGroups(allScopeGroups).filter((project) => chosenProjectScopeKeys.includes(project.projectKey), ); const chosenScopeProjectKeys = @@ -1322,6 +1396,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve draggableThreadKeys, activeReorderableThreadKeys, activeThreads, + activeGatheredByThreadKey, workingThreads, snoozedThreads, settledThreads, @@ -1370,6 +1445,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : null, keepEmptyFolders: (group) => scopedProjectGroups.length > 0 || (group.pinned && !group.archived), + gatherGroups: gatherProjectThreads + ? projectGroups.filter((group) => group.memberProjects.some(isCoveringProject)) + : NO_GATHER_GROUPS, }); // Ranked across environments as the palette ranks them, so one @@ -2043,6 +2121,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectFolders ?.map((folder) => `${folder.group.projectKey}:${folder.threads.length}`) .join("\n") ?? "", + // Gathered name rows come and go without moving any thread row. + [...activeGatheredByThreadKey].flatMap(([key, { first }]) => (first ? [key] : [])).join("\n"), visibleDraftSessionCount, routeDraftIdForRows ?? "", ].join("\0"); @@ -3224,7 +3304,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (project) handleProjectSettings(event, project); }} > - + {project ? ( ) : ( @@ -3484,6 +3564,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve section: SidebarSection, // The tree row of the project folder this row sits in. folderRow?: string, + // Sits among its group's gathered threads in the active list. + gathered?: { readonly last: boolean }, ) => { const threadKey = scopedThreadKey( scopeThreadRef(thread.environmentId, thread.id), @@ -3509,6 +3591,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } thread={thread} variant={rowVariant} + gathered={gathered && (gathered.last ? "last" : "member")} navigationParent={ folderRow ?? (section === "working" || @@ -3617,7 +3700,27 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (item.kind === "thread") { // Folders draw active rows in their own place below. if (projectFolders !== null && item.section === "active") continue; - items.push(renderThreadRow(threadByKey.get(item.key)!, item.section)); + const gathered = + item.section === "active" + ? activeGatheredByThreadKey.get(item.key) + : undefined; + if (gathered?.first) { + items.push( + , + ); + } + items.push( + renderThreadRow( + threadByKey.get(item.key)!, + item.section, + undefined, + gathered, + ), + ); continue; } if (projectFolders !== null && item.marker === "active-placeholder") { diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 387c3b3d51868..a81f55832b50e 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -21,6 +21,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { MiddleTruncate } from "../ui/middle-truncate"; import { observeResize } from "~/lib/observeResize"; import { repositoryFilePath } from "@t3tools/client-runtime/state/thread-repositories"; +import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; const EMPTY_DIRECTORY_OVERRIDES: Record = {}; const VIRTUALIZE_AFTER_ROWS = 250; @@ -42,6 +43,8 @@ export interface ChangedFilesGroup { readonly relativePath: string | undefined; /** Shown in place of the files when they cannot be listed. */ readonly note?: string | undefined; + /** The repository's own project, named after its folder. */ + readonly project?: ProjectFaviconProject | undefined; } type ChangedFileContextMenuHandler = ( @@ -246,6 +249,15 @@ function ChangedFilesGroupSection(props: { /> {group.name} + {group.project ? ( + + + {group.project.title} + + ) : null} {hasNonZeroStat(group.totals) && ( diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index bce13bb454379..a38a9ecb0bb8b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -2298,6 +2298,49 @@ function ChangedFilesTimeline() { } describe("ChangedFilesCard", () => { + it("names a repository's own project after its folder row", async () => { + const file = (path: string) => ({ + path, + kind: "modified" as const, + additions: 1, + deletions: 0, + }); + const group = (name: string) => ({ + key: name, + name, + files: [file("README.md")], + totals: { count: 1, additions: 1, deletions: 0 }, + relativePath: name, + }); + await using screen = await render( + {}} + onOpenTurnDiff={() => {}} + />, + ); + const row = (name: string) => + screen.container.querySelector(`[data-changed-files-group="${name}"] > button`)!; + expect(row("api").textContent).toContain("apiASAPI service"); + expect(row("web").querySelector("[data-changed-files-group-project]")).toBeNull(); + }); + it.each(["folder", "all folders"])( "measures %s collapse and expansion in the same commit", async (toggle) => { diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 72fcf79013e87..6a3512d66550d 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -25,8 +25,11 @@ import { readResponseSubagents, useAssistantMessageText, useProject, + useProjects, useQuietThreadShell, } from "../../state/entities"; +import { findCoveredFolderProject } from "@t3tools/client-runtime/state/project-grouping"; +import { normalizeProjectPathForComparison } from "@t3tools/client-runtime/state/projects"; import { MessageCopyButton } from "./MessageCopyButton"; import { AssistantCitationSource } from "./AssistantCitationSource"; import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic"; @@ -485,6 +488,7 @@ function AssistantChangedFilesSectionInner({ ? { environmentId: thread.environmentId, projectId: thread.projectId } : null, ); + const projects = useProjects(); const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId); const repositoryRoot = useAtomValue( ctx.workspaceRoot @@ -512,16 +516,33 @@ function AssistantChangedFilesSectionInner({ relativePath: "", }, ]), - ...repositories.map((repository) => ({ - key: repository.scopeId, - name: repository.name, - files: repository.files, - totals: changedFileTotals(repository), - relativePath: repository.relativePath, - ...(repository.baselineMissing - ? { note: gt("This turn's changes in this repository cannot be listed.") } - : {}), - })), + ...repositories.map((repository) => { + const path = normalizeProjectPathForComparison(repository.repositoryPath); + const project = activeProject + ? findCoveredFolderProject( + activeProject.trackedFolders?.find( + (folder) => normalizeProjectPathForComparison(folder.path) === path, + ) ?? { path: repository.repositoryPath }, + activeProject.environmentId, + projects.filter( + (candidate) => + candidate.id !== activeProject.id || + candidate.environmentId !== activeProject.environmentId, + ), + ) + : undefined; + return { + key: repository.scopeId, + name: repository.name, + files: repository.files, + totals: changedFileTotals(repository), + relativePath: repository.relativePath, + ...(repository.baselineMissing + ? { note: gt("This turn's changes in this repository cannot be listed.") } + : {}), + ...(project ? { project } : {}), + }; + }), ]; const repositoryCwdByGroupKey = new Map( repositories?.map((repository) => [repository.scopeId as string, repository.cwd]), diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 97b278a463e9e..ace1717c412c4 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -544,6 +544,10 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.sidebarWorkingShelfEnabled !== DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? [gt("Working section")] : []), + ...(settings.sidebarGatherProjectThreads !== + DEFAULT_UNIFIED_SETTINGS.sidebarGatherProjectThreads + ? [gt("Gather multi-repo projects")] + : []), ...(settings.sidebarAutoSettleAfterDays !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? [gt("Auto-settle inactive threads")] : []), @@ -735,6 +739,7 @@ export function useSettingsRestore(onRestored?: () => void) { sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled, + sidebarGatherProjectThreads: DEFAULT_UNIFIED_SETTINGS.sidebarGatherProjectThreads, sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, sidebarAutoSettleKeepPullRequests: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests, sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, @@ -981,6 +986,39 @@ export function GeneralSettingsPanel() { /> } /> + + Threads that show a status come first. Below them, each project with several + repositories gathers its threads, and those of its repositories' own projects, under + its name. + + } + resetAction={ + settings.sidebarGatherProjectThreads !== + DEFAULT_UNIFIED_SETTINGS.sidebarGatherProjectThreads ? ( + + updateSettings({ + sidebarGatherProjectThreads: + DEFAULT_UNIFIED_SETTINGS.sidebarGatherProjectThreads, + }) + } + /> + ) : null + } + control={ + + updateSettings({ sidebarGatherProjectThreads: Boolean(checked) }) + } + aria-label={gt("Gather multi-repo projects")} + /> + } + /> diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index 2bbdd7867c3c7..d7ecf9bc1f440 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -69,6 +69,7 @@ function group( environmentId: project.environmentId, projectId: project.id, })), + folded: [], groupedProjectCount: members.length, environmentPresence: "mixed", allRemoteMembersAreDesktopLocal: false, diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.ts index 1748f37690ebb..972b2db161ee6 100644 --- a/apps/web/src/components/settings/scopedSettings.test.ts +++ b/apps/web/src/components/settings/scopedSettings.test.ts @@ -91,6 +91,7 @@ const group: SidebarProjectSnapshot = { { environmentId: server.environmentId, projectId }, { environmentId: laptop.environmentId, projectId: laptopProjectId }, ], + folded: [], groupedProjectCount: 2, environmentPresence: "remote-only", allRemoteMembersAreDesktopLocal: false, diff --git a/apps/web/src/components/settings/settingsScope.test.ts b/apps/web/src/components/settings/settingsScope.test.ts index 60e69b7714f11..88a11e01b79d1 100644 --- a/apps/web/src/components/settings/settingsScope.test.ts +++ b/apps/web/src/components/settings/settingsScope.test.ts @@ -49,6 +49,7 @@ function group( environmentId: project.environmentId, projectId: project.id, })), + folded: [], groupedProjectCount: members.length, environmentPresence: "mixed", allRemoteMembersAreDesktopLocal: false, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 1f38ed958d368..8277337ee87dc 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -500,6 +500,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: [msg("hide fold running monitoring threads inbox sidebar shelf")], }, + { + id: "gather-project-threads", + title: msg("Gather multi-repo projects"), + to: "/settings/general", + searchTerms: [msg("group repositories status first sidebar fold projects threads")], + }, { id: "boring-sidebar", title: msg("Boring sidebar (group by project)"), diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx index 7ebda48e5b89a..db3173f2b4022 100644 --- a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx @@ -136,3 +136,34 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead ); }); + +/** A project's name above the threads it gathers in the default sidebar's active list. */ +export const SidebarGatheredHeader = memo(function SidebarGatheredHeader(props: { + group: SidebarProjectSnapshot; + onContextMenu: ( + group: SidebarProjectSnapshot, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => void; +}) { + const { group } = props; + return ( +
  • { + event.preventDefault(); + props.onContextMenu( + group, + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ); + }} + > + + + {group.displayName} + +
  • + ); +}); diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 2aa9be4c244a6..e94f11e3bdab1 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -83,7 +83,7 @@ import { vcsEnvironment, vcsBranchRevalidation } from "../../state/vcs"; import { useSidebarLinkedIssueState } from "../../state/issues"; import { useEnvironmentQuery } from "../../state/query"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; -import { formatRelativeTime, parseTimestampDate } from "../../timestampFormat"; +import { formatRelativeTime } from "../../timestampFormat"; import type { SidebarThreadSummary } from "../../types"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { cn } from "~/lib/utils"; @@ -92,6 +92,7 @@ import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { animateSidebarLayoutChanges, hasUnseenCompletion, + isSidebarThreadWoke, resolveSidebarRowAccessibility, type SidebarDropVerb, resolveSidebarRowStatus, @@ -585,6 +586,8 @@ type SidebarThreadRowProps = { // "folder" is a one-line row inside a boring sidebar project folder; // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; + // Indents a card under its group's name row, beside a line that ends at the group's last card. + gathered?: "member" | "last" | undefined; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; @@ -773,12 +776,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); const status = resolveSidebarRowStatus({ ...thread, lastVisitedAt }); - const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt); - const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt); - const isWoke = - wokeAtDate !== null && - (lastVisitedDate === null || lastVisitedDate < wokeAtDate) && - thread.settledOverride !== "settled"; + const isWoke = isSidebarThreadWoke({ ...thread, lastVisitedAt }, props.wokeAt); const shouldRecede = shouldRecedeSidebarThread({ status, isUnread, @@ -1527,9 +1525,19 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn( "list-none py-0.5 [content-visibility:auto] [contain-intrinsic-size:auto_78px]", metaLineEmpty && "[contain-intrinsic-size:auto_60px]", + props.gathered && "relative ps-(--sidebar-gathered-indent)", sortable?.isDragging && "relative z-20", )} > + {props.gathered ? ( + + ) : null} { }, ); + it("keeps a folded project pickable on its own, under the project that covers its folder", () => { + const shop = makeProject({ + id: ProjectId.make("shop"), + title: "shop", + workspaceRoot: "/work/shop", + trackedFolders: [{ path: "/work/shop/api", name: "api", discovered: true }], + }); + const api = makeProject({ + id: ProjectId.make("api"), + title: "api", + workspaceRoot: "/work/shop/api", + repositoryIdentity, + }); + const build = (foldCoveredProjects: boolean) => + buildSidebarProjectSnapshots({ + projects: [shop, api], + foldCoveredProjects, + settings: defaultGroupingSettings, + primaryEnvironmentId, + resolveEnvironmentLabel: () => null, + }); + expect(build(false).map((group) => group.displayName)).toEqual(["shop", "api"]); + + const [group, ...rest] = build(true); + expect(rest).toEqual([]); + expect(group?.memberProjectRefs.map((ref) => ref.projectId)).toEqual(["shop", "api"]); + // A scope saved for api still names api's own threads. + expect(group?.folded.map((folded) => [folded.projectKey, folded.folderName])).toEqual([ + [deriveLogicalProjectKeyFromSettings(api, defaultGroupingSettings), "api"], + ]); + expect(group?.folded[0]?.memberProjectRefs.map((ref) => ref.projectId)).toEqual(["api"]); + }); + it("prefers an existing ordinary repository scope over a scratch alias", () => { const scratch = makeProject({ isScratch: true, repositoryIdentity }); const ordinary = makeProject({ diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.ts index 7a0036d35786d..840c7a8beae31 100644 --- a/apps/web/src/hooks/useSidebarProjectGroups.ts +++ b/apps/web/src/hooks/useSidebarProjectGroups.ts @@ -39,6 +39,7 @@ export function useSidebarProjectGroups() { { projects: sortOrder === "manual" ? orderedProjects : projects, groupScratchProjects: true, + foldCoveredProjects: true, settings: groupingSettings, primaryEnvironmentId, resolveEnvironmentLabel: (environmentId) => labels.get(environmentId) ?? null, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7900e73186091..2fb9992086a18 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -10096,6 +10096,7 @@ "1fb14292c4159760": "Projektgruppierung", "6147d6fc04079525": "Projektreihenfolge", "bdf39fd139a04325": "Bereich „In Arbeit“", + "a4469243f88266c2": "Multi-Repo-Projekte bündeln", "f760219456ce86fc": "Inaktive Threads automatisch erledigen", "33638d35a13557cc": "Threads mit PR behalten", "e89c6d8932de7863": "Gemergte Threads automatisch erledigen", @@ -10139,6 +10140,7 @@ "cd5452cc9e13c818": "Projektgruppierung", "cfb01b8a2a3361fb": "Projektreihenfolge auf Standard zurücksetzen", "26abcbe322049a8a": "Bereich „In Arbeit“ auf Standard zurücksetzen", + "a4075cfe030dbc3d": "Bündeln von Multi-Repo-Projekten auf Standard zurücksetzen", "76f3c3e2f8dd0120": "Bestätigungen", "caed837d6dc42548": "Bestätigung beim Loslösen auf Standard zurücksetzen", "859e386f8af841f0": "Loslösen von Threads bestätigen", @@ -10248,6 +10250,7 @@ "83ca942c7163904f": "Gleiche Repositorys aus verschiedenen Umgebungen zusammenfassen.", "609da998ca13521e": "Reihenfolge der Projekte in der Projektauswahl der Seitenleiste und in der Befehlspalette.", "b4c541137a76b351": "Laufende und überwachende Threads im Bereich „In Arbeit“ bündeln. Sie rücken im Posteingang wieder nach oben, sobald sie dich brauchen. Die schlichte Seitenleiste unter Labs hat keinen Bereich „In Arbeit“.", + "2eab493d23bce627": "Threads, die einen Status zeigen, stehen oben. Darunter sammelt jedes Projekt mit mehreren Repositorys seine Threads und die der eigenen Projekte seiner Repositorys unter seinem Namen.", "e815f49e5abedcfd": "Vor dem Loslösen eines Threads aus dem Bereich „Angeheftet“ nachfragen.", "41210f99adeeba78": "Einen zweiten Klick auf die Archivieren-Aktion verlangen, bevor ein Thread archiviert wird.", "84f3d2cefc8d2a74": "Vor dem Löschen eines Threads samt Chatverlauf nachfragen.", @@ -11844,6 +11847,7 @@ "6751449c6188912d": "nutzung kontingent rate limit zurücksetzen aufwecken wiederherstellen fortsetzen", "0aedae6a82c09429": "nutzung kontingent rate limit zurücksetzen wiederherstellen fortsetzen", "85dbcfec2d41f534": "ausblenden einklappen laufende überwachende threads posteingang seitenleiste in arbeit ablage", + "975216b509622578": "gruppieren repositorys status zuerst seitenleiste bündeln projekte threads", "405a2295152c9d77": "beta ordner projektbaum klassische seitenleiste", "de42c4690914cee4": "beta schlichte seitenleiste ordner zeilen mehrzeilig branch pull request details", "8f71bc7c325e23e3": "tool-aufrufe ausblenden befehle bearbeitungen suchen arbeitsprotokoll aktivität ruhiger chat zen nur endgültige antworten", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 5bdd7c383d319..c4823ca71bd05 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -10105,6 +10105,7 @@ "1fb14292c4159760": "Project Grouping", "6147d6fc04079525": "Project order", "bdf39fd139a04325": "Working section", + "a4469243f88266c2": "Gather multi-repo projects", "f760219456ce86fc": "Auto-settle inactive threads", "33638d35a13557cc": "Keep threads with a PR", "e89c6d8932de7863": "Auto-settle merged threads", @@ -10148,6 +10149,7 @@ "cd5452cc9e13c818": "Project grouping", "cfb01b8a2a3361fb": "Reset project order to default", "26abcbe322049a8a": "Reset working section to default", + "a4075cfe030dbc3d": "Reset multi-repo project gathering to default", "76f3c3e2f8dd0120": "Confirmations", "caed837d6dc42548": "Reset unpin confirmation to default", "859e386f8af841f0": "Confirm thread unpinning", @@ -10257,6 +10259,7 @@ "83ca942c7163904f": "Combine matching repositories across environments.", "609da998ca13521e": "Order of projects in the sidebar project picker and command palette.", "b4c541137a76b351": "Fold working and monitoring threads into a Working section. They return to the top of the inbox when they need you. The boring sidebar in Labs has no Working section.", + "2eab493d23bce627": "Threads that show a status come first. Below them, each project with several repositories gathers its threads, and those of its repositories' own projects, under its name.", "e815f49e5abedcfd": "Ask before unpinning a thread from the pinned section.", "41210f99adeeba78": "Require a second click on the inline archive action before a thread is archived.", "84f3d2cefc8d2a74": "Ask before deleting a thread and its chat history.", @@ -11852,6 +11855,7 @@ "6751449c6188912d": "usage quota rate limit reset wake recover continue", "0aedae6a82c09429": "usage quota rate limit reset recover continue", "85dbcfec2d41f534": "hide fold running monitoring threads inbox sidebar shelf", + "975216b509622578": "group repositories status first sidebar fold projects threads", "405a2295152c9d77": "beta folders project tree classic sidebar", "de42c4690914cee4": "beta boring sidebar folder rows multiline branch pull request details", "8f71bc7c325e23e3": "hide tool calls commands edits searches work log activity quiet chat zen final answers only", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 91dbb2b07f50f..1d6bbbe0ec13e 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -10093,6 +10093,7 @@ "1fb14292c4159760": "Agrupación de proyectos", "6147d6fc04079525": "Orden de proyectos", "bdf39fd139a04325": "Sección En curso", + "a4469243f88266c2": "Agrupar proyectos con varios repositorios", "f760219456ce86fc": "Resolver automáticamente los hilos inactivos", "33638d35a13557cc": "Mantener los hilos con PR", "e89c6d8932de7863": "Resolver automáticamente los hilos fusionados", @@ -10136,6 +10137,7 @@ "cd5452cc9e13c818": "Agrupación de proyectos", "cfb01b8a2a3361fb": "Restablecer el orden de proyectos al valor predeterminado", "26abcbe322049a8a": "Restablecer la sección En curso al valor predeterminado", + "a4075cfe030dbc3d": "Restablecer la agrupación de proyectos con varios repositorios al valor predeterminado", "76f3c3e2f8dd0120": "Confirmaciones", "caed837d6dc42548": "Restablecer la confirmación al desfijar al valor predeterminado", "859e386f8af841f0": "Confirmar al desfijar hilos", @@ -10245,6 +10247,7 @@ "83ca942c7163904f": "Combina los repositorios coincidentes de distintos entornos.", "609da998ca13521e": "Orden de los proyectos en el selector de la barra lateral y en la paleta de comandos.", "b4c541137a76b351": "Agrupa los hilos activos y en seguimiento en la sección En curso. Vuelven arriba de la bandeja de entrada cuando te necesitan. La barra lateral simple (en Experimentos) no tiene sección En curso.", + "2eab493d23bce627": "Los hilos que muestran un estado aparecen primero. Debajo, cada proyecto con varios repositorios reúne bajo su nombre sus hilos y los de los proyectos propios de sus repositorios.", "e815f49e5abedcfd": "Pregunta antes de desfijar un hilo de la sección de fijados.", "41210f99adeeba78": "Pide un segundo clic en la acción de archivar antes de archivar un hilo.", "84f3d2cefc8d2a74": "Pregunta antes de eliminar un hilo y su historial de chat.", @@ -11837,6 +11840,7 @@ "6751449c6188912d": "uso cuota límite de uso restablecer reactivar recuperar continuar", "0aedae6a82c09429": "uso cuota límite de uso restablecer recuperar continuar", "85dbcfec2d41f534": "ocultar agrupar en ejecución seguimiento hilos bandeja de entrada barra lateral estante en curso", + "975216b509622578": "agrupar repositorios estado primero barra lateral reunir proyectos hilos", "405a2295152c9d77": "beta carpetas proyecto árbol barra lateral clásica", "de42c4690914cee4": "beta barra lateral simple boring sidebar filas de carpetas multilínea rama pull request detalles", "8f71bc7c325e23e3": "ocultar llamadas a herramientas comandos ediciones búsquedas registro de trabajo actividad chat silencioso zen solo respuestas finales", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f5cf7e62a4744..2c6fcb95e6d10 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -10095,6 +10095,7 @@ "1fb14292c4159760": "Regroupement des projets", "6147d6fc04079525": "Ordre des projets", "bdf39fd139a04325": "Section En cours", + "a4469243f88266c2": "Regrouper les projets multi-dépôts", "f760219456ce86fc": "Clore automatiquement les fils inactifs", "33638d35a13557cc": "Garder les fils avec une PR", "e89c6d8932de7863": "Clore automatiquement les fils fusionnés", @@ -10138,6 +10139,7 @@ "cd5452cc9e13c818": "Regroupement des projets", "cfb01b8a2a3361fb": "Réinitialiser l’ordre des projets à la valeur par défaut", "26abcbe322049a8a": "Réinitialiser la section En cours à la valeur par défaut", + "a4075cfe030dbc3d": "Réinitialiser le regroupement des projets multi-dépôts à la valeur par défaut", "76f3c3e2f8dd0120": "Confirmations", "caed837d6dc42548": "Réinitialiser la confirmation avant de désépingler à la valeur par défaut", "859e386f8af841f0": "Confirmer avant de désépingler un fil", @@ -10247,6 +10249,7 @@ "83ca942c7163904f": "Regroupe les dépôts identiques de tous les environnements.", "609da998ca13521e": "Ordre des projets dans le sélecteur de la barre latérale et dans la palette de commandes.", "b4c541137a76b351": "Regroupe les fils en cours et en surveillance dans une section En cours. Ils reviennent en haut de la boîte de réception quand ils ont besoin de vous. La barre latérale classique de Labs n’a pas de section En cours.", + "2eab493d23bce627": "Les fils qui affichent un statut passent en premier. En dessous, chaque projet à plusieurs dépôts regroupe sous son nom ses fils et ceux des projets propres à ses dépôts.", "e815f49e5abedcfd": "Demande confirmation avant de désépingler un fil.", "41210f99adeeba78": "Exige un second clic sur le bouton d’archivage du fil avant de l’archiver.", "84f3d2cefc8d2a74": "Demande confirmation avant de supprimer un fil et son historique de discussion.", @@ -11842,6 +11845,7 @@ "6751449c6188912d": "utilisation quota limite de débit réinitialisation réveil récupérer continuer", "0aedae6a82c09429": "utilisation quota limite de débit réinitialisation récupérer continuer", "85dbcfec2d41f534": "masquer regrouper en cours surveillance fils boîte de réception barre latérale étagère", + "975216b509622578": "grouper dépôts statut premier barre latérale regrouper projets fils", "405a2295152c9d77": "bêta dossiers arborescence de projets barre latérale classique", "de42c4690914cee4": "bêta barre latérale classique lignes de dossier multiligne branche détails pull request", "8f71bc7c325e23e3": "masquer appels d’outils commandes modifications recherches journal de travail activité discussion silencieuse zen réponses finales uniquement", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 7e3be343b068b..b29e17bdf1c3d 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -10048,6 +10048,7 @@ "1fb14292c4159760": "プロジェクトのグループ化", "6147d6fc04079525": "プロジェクトの並び順", "bdf39fd139a04325": "「作業中」セクション", + "a4469243f88266c2": "複数リポジトリのプロジェクトをまとめる", "f760219456ce86fc": "非アクティブなスレッドを自動的に対応済みにする", "33638d35a13557cc": "PR のあるスレッドは残す", "e89c6d8932de7863": "マージされたスレッドを自動的に対応済みにする", @@ -10091,6 +10092,7 @@ "cd5452cc9e13c818": "プロジェクトのグループ化", "cfb01b8a2a3361fb": "プロジェクトの並び順をデフォルトにリセット", "26abcbe322049a8a": "「作業中」セクションをデフォルトにリセット", + "a4075cfe030dbc3d": "複数リポジトリのプロジェクトのまとめをデフォルトにリセット", "76f3c3e2f8dd0120": "確認ダイアログ", "caed837d6dc42548": "ピン留め解除の確認をデフォルトにリセット", "859e386f8af841f0": "スレッドのピン留め解除を確認", @@ -10200,6 +10202,7 @@ "83ca942c7163904f": "環境をまたいで同じリポジトリをまとめて表示します。", "609da998ca13521e": "サイドバーのプロジェクト選択メニューとコマンドパレットでの表示順です。", "b4c541137a76b351": "作業中と監視中のスレッドを「作業中」セクションにまとめます。対応が必要になると受信トレイの先頭に戻ります。「試験的機能」のシンプルなサイドバーには「作業中」セクションはありません。", + "2eab493d23bce627": "ステータスを表示しているスレッドが先頭に来ます。その下では、複数のリポジトリを持つ各プロジェクトが、自身のスレッドと各リポジトリ専用のプロジェクトのスレッドを自分の名前の下にまとめます。", "e815f49e5abedcfd": "スレッドのピン留めを解除する前に確認します。", "41210f99adeeba78": "インラインのアーカイブボタンは、もう一度クリックするまでスレッドをアーカイブしません。", "84f3d2cefc8d2a74": "スレッドとそのチャット履歴を削除する前に確認します。", @@ -11793,6 +11796,7 @@ "6751449c6188912d": "使用量 クォータ レート制限 リセット 再開 復旧 続行 usage limit", "0aedae6a82c09429": "使用量 クォータ レート制限 リセット 復旧 続行 usage limit", "85dbcfec2d41f534": "非表示 折りたたみ 実行中 監視中 スレッド 受信トレイ サイドバー 棚 作業中 working", + "975216b509622578": "グループ リポジトリ ステータス 先頭 サイドバー まとめる プロジェクト スレッド", "405a2295152c9d77": "ベータ フォルダー プロジェクト ツリー クラシック サイドバー beta folders", "de42c4690914cee4": "ベータ シンプルなサイドバー フォルダー 行 複数行 ブランチ プルリクエスト 詳細 beta boring sidebar", "8f71bc7c325e23e3": "非表示 ツール呼び出し コマンド 編集 検索 作業ログ アクティビティ 静か チャット zen 最終回答のみ tool calls", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ef69858aead11..9ef752ae0b9c7 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -10050,6 +10050,7 @@ "1fb14292c4159760": "프로젝트 그룹화", "6147d6fc04079525": "프로젝트 순서", "bdf39fd139a04325": "작업 중 섹션", + "a4469243f88266c2": "여러 저장소 프로젝트 모으기", "f760219456ce86fc": "비활성 스레드 자동 정리", "33638d35a13557cc": "PR이 있는 스레드 유지", "e89c6d8932de7863": "병합된 스레드 자동 정리", @@ -10093,6 +10094,7 @@ "cd5452cc9e13c818": "프로젝트 그룹화", "cfb01b8a2a3361fb": "프로젝트 순서 기본값으로 재설정", "26abcbe322049a8a": "작업 중 섹션 기본값으로 재설정", + "a4075cfe030dbc3d": "여러 저장소 프로젝트 모으기 기본값으로 재설정", "76f3c3e2f8dd0120": "확인 요청", "caed837d6dc42548": "고정 해제 확인 기본값으로 재설정", "859e386f8af841f0": "스레드 고정 해제 확인", @@ -10202,6 +10204,7 @@ "83ca942c7163904f": "여러 환경에 있는 같은 저장소를 하나로 묶어 표시합니다.", "609da998ca13521e": "사이드바 프로젝트 선택기와 명령 팔레트에 표시되는 프로젝트 순서입니다.", "b4c541137a76b351": "작업 중이거나 모니터링 중인 스레드를 작업 중 섹션으로 접어 둡니다. 응답이 필요해지면 인박스 맨 위로 다시 올라옵니다. 실험 기능의 단순 사이드바에는 작업 중 섹션이 없습니다.", + "2eab493d23bce627": "상태가 표시된 스레드가 먼저 옵니다. 그 아래에서는 여러 저장소가 있는 각 프로젝트가 자신의 스레드와 각 저장소 전용 프로젝트의 스레드를 자신의 이름 아래에 모읍니다.", "e815f49e5abedcfd": "고정 섹션에서 스레드 고정을 해제하기 전에 확인을 요청합니다.", "41210f99adeeba78": "인라인 보관 버튼을 한 번 더 클릭해야 스레드가 보관됩니다.", "84f3d2cefc8d2a74": "스레드와 채팅 기록을 삭제하기 전에 확인을 요청합니다.", @@ -11789,6 +11792,7 @@ "6751449c6188912d": "사용량 할당량 속도 제한 초기화 깨우기 복구 계속", "0aedae6a82c09429": "사용량 할당량 속도 제한 초기화 복구 계속", "85dbcfec2d41f534": "숨기기 접기 실행 중 모니터링 스레드 인박스 사이드바 선반 작업 중", + "975216b509622578": "그룹 저장소 상태 먼저 사이드바 모으기 프로젝트 스레드", "405a2295152c9d77": "베타 폴더 프로젝트 트리 클래식 사이드바", "de42c4690914cee4": "베타 단순 사이드바 폴더 행 여러 줄 브랜치 풀 리퀘스트 세부 정보", "8f71bc7c325e23e3": "숨기기 도구 호출 명령 편집 검색 작업 로그 활동 조용한 채팅 젠 최종 답변만", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2f82a27a416..6c1d159166bfa 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -10095,6 +10095,7 @@ "1fb14292c4159760": "Agrupamento de projetos", "6147d6fc04079525": "Ordem dos projetos", "bdf39fd139a04325": "Seção Trabalhando", + "a4469243f88266c2": "Agrupar projetos com vários repositórios", "f760219456ce86fc": "Concluir automaticamente threads inativas", "33638d35a13557cc": "Manter threads com PR", "e89c6d8932de7863": "Concluir automaticamente threads mescladas", @@ -10138,6 +10139,7 @@ "cd5452cc9e13c818": "Agrupamento de projetos", "cfb01b8a2a3361fb": "Redefinir a ordem dos projetos para o padrão", "26abcbe322049a8a": "Redefinir a seção Trabalhando para o padrão", + "a4075cfe030dbc3d": "Redefinir o agrupamento de projetos com vários repositórios para o padrão", "76f3c3e2f8dd0120": "Confirmações", "caed837d6dc42548": "Redefinir a confirmação ao desafixar para o padrão", "859e386f8af841f0": "Confirmar ao desafixar threads", @@ -10247,6 +10249,7 @@ "83ca942c7163904f": "Combina repositórios correspondentes entre ambientes.", "609da998ca13521e": "Ordem dos projetos no seletor da barra lateral e na paleta de comandos.", "b4c541137a76b351": "Agrupa as threads em andamento e em monitoramento em uma seção Trabalhando. Elas voltam ao topo da caixa de entrada quando precisam de você. A barra lateral sem graça do Labs não tem seção Trabalhando.", + "2eab493d23bce627": "As threads que mostram um status vêm primeiro. Abaixo delas, cada projeto com vários repositórios reúne sob seu nome as próprias threads e as dos projetos próprios de seus repositórios.", "e815f49e5abedcfd": "Pergunta antes de desafixar uma thread da seção de fixadas.", "41210f99adeeba78": "Exige um segundo clique para confirmar antes de arquivar uma thread.", "84f3d2cefc8d2a74": "Pergunta antes de excluir uma thread e o histórico dela.", @@ -11842,6 +11845,7 @@ "6751449c6188912d": "uso cota limite de taxa redefinir despertar recuperar continuar", "0aedae6a82c09429": "uso cota limite de taxa redefinir recuperar continuar", "85dbcfec2d41f534": "ocultar agrupar em execução monitoramento threads caixa de entrada barra lateral prateleira", + "975216b509622578": "agrupar repositórios status primeiro barra lateral reunir projetos threads", "405a2295152c9d77": "beta pastas projeto árvore barra lateral clássica", "de42c4690914cee4": "beta barra lateral sem graça pasta linhas várias linhas branch pull request detalhes", "8f71bc7c325e23e3": "ocultar chamadas de ferramentas comandos edições pesquisas registro de trabalho atividade chat silencioso zen só respostas finais", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2891cb8165d7c..7fb3ab021d6b7 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -10098,6 +10098,7 @@ "1fb14292c4159760": "Группировка проектов", "6147d6fc04079525": "Порядок проектов", "bdf39fd139a04325": "Раздел «В работе»", + "a4469243f88266c2": "Собирать проекты с несколькими репозиториями", "f760219456ce86fc": "Авторазбор неактивных тредов", "33638d35a13557cc": "Сохранять треды с PR", "e89c6d8932de7863": "Авторазбор слитых тредов", @@ -10141,6 +10142,7 @@ "cd5452cc9e13c818": "Группировка проектов", "cfb01b8a2a3361fb": "Сбросить порядок проектов к значению по умолчанию", "26abcbe322049a8a": "Сбросить раздел «В работе» к значению по умолчанию", + "a4075cfe030dbc3d": "Сбросить сбор проектов с несколькими репозиториями к значению по умолчанию", "76f3c3e2f8dd0120": "Подтверждения", "caed837d6dc42548": "Сбросить подтверждение открепления к значению по умолчанию", "859e386f8af841f0": "Подтверждать открепление тредов", @@ -10250,6 +10252,7 @@ "83ca942c7163904f": "Объединяет одинаковые репозитории из разных окружений.", "609da998ca13521e": "Порядок проектов в меню выбора проекта на боковой панели и в палитре команд.", "b4c541137a76b351": "Сворачивает выполняющиеся и отслеживающие треды в раздел «В работе». Они возвращаются наверх входящих, когда требуется ваше участие. В простой боковой панели из раздела «Эксперименты» раздела «В работе» нет.", + "2eab493d23bce627": "Треды со статусом идут первыми. Ниже каждый проект с несколькими репозиториями собирает под своим именем свои треды и треды собственных проектов своих репозиториев.", "e815f49e5abedcfd": "Запрашивает подтверждение перед откреплением треда.", "41210f99adeeba78": "Требует повторного нажатия на кнопку архивации в строке, прежде чем тред будет архивирован.", "84f3d2cefc8d2a74": "Запрашивает подтверждение перед удалением треда и его истории.", @@ -11843,6 +11846,7 @@ "6751449c6188912d": "использование квота лимит запросов сброс пробуждение восстановить продолжить", "0aedae6a82c09429": "использование квота лимит запросов сброс восстановить продолжить", "85dbcfec2d41f534": "скрыть свернуть выполняющиеся отслеживающие треды входящие боковая панель полка в работе", + "975216b509622578": "группировать репозитории статус сначала боковая панель собирать проекты треды", "405a2295152c9d77": "бета папки дерево проектов классическая боковая панель", "de42c4690914cee4": "бета простая боковая панель строки папок многострочные ветка пул-реквест подробности", "8f71bc7c325e23e3": "скрыть вызовы инструментов команды правки поиски журнал работы активность тихий чат дзен только итоговые ответы", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c792d6fb4a981..82f325dac43ef 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -10103,6 +10103,7 @@ "1fb14292c4159760": "Projektgruppering", "6147d6fc04079525": "Projektordning", "bdf39fd139a04325": "Avsnittet Arbetar", + "a4469243f88266c2": "Samla projekt med flera repon", "f760219456ce86fc": "Markera inaktiva trådar som klara automatiskt", "33638d35a13557cc": "Behåll trådar med en PR", "e89c6d8932de7863": "Markera mergade trådar som klara automatiskt", @@ -10146,6 +10147,7 @@ "cd5452cc9e13c818": "Projektgruppering", "cfb01b8a2a3361fb": "Återställ projektordning till standard", "26abcbe322049a8a": "Återställ avsnittet Arbetar till standard", + "a4075cfe030dbc3d": "Återställ samling av projekt med flera repon till standard", "76f3c3e2f8dd0120": "Bekräftelser", "caed837d6dc42548": "Återställ bekräftelse vid lossning till standard", "859e386f8af841f0": "Bekräfta lossning av trådar", @@ -10255,6 +10257,7 @@ "83ca942c7163904f": "Slå ihop matchande repon från olika miljöer.", "609da998ca13521e": "Ordningen på projekt i sidofältets projektväljare och kommandopaletten.", "b4c541137a76b351": "Fäll in arbetande och övervakande trådar i avsnittet Arbetar. De återvänder överst i inkorgen när de behöver dig. Det enkla sidofältet i Labs har inget avsnitt Arbetar.", + "2eab493d23bce627": "Trådar som visar en status kommer först. Under dem samlar varje projekt med flera repon sina trådar, och trådarna i reponas egna projekt, under sitt namn.", "e815f49e5abedcfd": "Fråga innan en tråd lossas från avsnittet för fästa trådar.", "41210f99adeeba78": "Kräv ett andra klick på arkiveringsåtgärden innan en tråd arkiveras.", "84f3d2cefc8d2a74": "Fråga innan en tråd och dess chatthistorik tas bort.", @@ -11850,6 +11853,7 @@ "6751449c6188912d": "användning kvot hastighetsbegränsning återställning vakna återhämta fortsätt", "0aedae6a82c09429": "användning kvot hastighetsbegränsning återställning återhämta fortsätt", "85dbcfec2d41f534": "dölj fäll ihop pågående bevakning trådar inkorg sidofält hylla", + "975216b509622578": "gruppera repon status först sidofält samla projekt trådar", "405a2295152c9d77": "beta mappar projektträd klassiskt sidofält", "de42c4690914cee4": "beta enkelt sidofält mapprader flera rader gren pull request detaljer", "8f71bc7c325e23e3": "dölj verktygsanrop kommandon redigeringar sökningar arbetslogg aktivitet tyst chatt zen bara slutliga svar", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cd80e9a35102a..693a00223fb19 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -10111,6 +10111,7 @@ "1fb14292c4159760": "项目分组", "6147d6fc04079525": "项目排序", "bdf39fd139a04325": "运行中分组", + "a4469243f88266c2": "汇集多仓库项目", "f760219456ce86fc": "自动收尾不活跃会话", "33638d35a13557cc": "保留有关联 PR 的会话", "e89c6d8932de7863": "合并后自动收尾会话", @@ -10154,6 +10155,7 @@ "cd5452cc9e13c818": "项目分组", "cfb01b8a2a3361fb": "重置项目排序为默认值", "26abcbe322049a8a": "重置“运行中”分区为默认值", + "a4075cfe030dbc3d": "重置“汇集多仓库项目”为默认值", "76f3c3e2f8dd0120": "确认操作", "caed837d6dc42548": "重置取消置顶确认为默认值", "859e386f8af841f0": "确认取消置顶会话", @@ -10263,6 +10265,7 @@ "83ca942c7163904f": "将不同环境中的相同仓库合并显示。", "609da998ca13521e": "侧边栏项目选择器和命令面板中的项目排序。", "b4c541137a76b351": "将正在执行和监控的会话收起到“运行中”分组。需要你处理时,它们会回到收件箱顶部。实验功能中的简洁侧边栏不显示此分组。", + "2eab493d23bce627": "显示状态的会话排在最前。其下,每个包含多个仓库的项目会把自己的会话以及其各仓库自身项目的会话汇集在自己的名称下。", "e815f49e5abedcfd": "取消置顶会话前询问。", "41210f99adeeba78": "点击会话行内的归档按钮后,需再次点击才会归档。", "84f3d2cefc8d2a74": "删除会话及其聊天记录前询问。", @@ -11867,6 +11870,7 @@ "6751449c6188912d": "用量 配额 速率限制 重置 唤醒 恢复 继续", "0aedae6a82c09429": "用量 配额 速率限制 重置 恢复 继续", "85dbcfec2d41f534": "隐藏 收起 运行中 监控中 会话 收件箱 侧边栏 分组", + "975216b509622578": "分组 仓库 状态 优先 侧边栏 汇集 项目 会话", "405a2295152c9d77": "测试版 文件夹 项目 树 经典 侧边栏", "de42c4690914cee4": "测试版 简洁侧边栏 文件夹 行 多行 分支 PR 详情", "8f71bc7c325e23e3": "隐藏 工具调用 命令 编辑 搜索 工作日志 活动 安静 聊天 专注 仅最终回答", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 15380512f4060..e63263f541644 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -109,6 +109,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil var(--sidebar) ); --sidebar-row-content-inset: 0.625rem; + /* How far a project shown as part of another sits in: gathered threads and the project menu. */ + --sidebar-gathered-indent: 0.75rem; --command-shell-inset: 0.5rem; --command-content-inset: 1rem; --floating-content-inset: 0.75rem; diff --git a/apps/web/src/sidebarProjectGrouping.ts b/apps/web/src/sidebarProjectGrouping.ts index aaf4bcf57b1e0..851748497375a 100644 --- a/apps/web/src/sidebarProjectGrouping.ts +++ b/apps/web/src/sidebarProjectGrouping.ts @@ -9,6 +9,7 @@ import { isPickableProjectMember, resolveScratchProjectScopeKey, selectGroupDefaultProject, + type ProjectGroup, type ProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { msg } from "gt-react"; @@ -49,11 +50,17 @@ export interface SidebarProjectSnapshot extends Project { allRemoteMembersAreWsl: boolean; memberProjects: readonly SidebarProjectGroupMember[]; memberProjectRefs: readonly ScopedProjectRef[]; + /** Projects shown as part of this one because it covers their folder. */ + folded: readonly FoldedSidebarProjectSnapshot[]; remoteEnvironmentLabels: readonly string[]; pinned: boolean; archived: boolean; } +export interface FoldedSidebarProjectSnapshot extends SidebarProjectSnapshot { + folderName: string; +} + export function projectGroupsSpanEnvironments( groups: ReadonlyArray>, ): boolean { @@ -147,6 +154,7 @@ export function buildSidebarProjectSnapshots( projects: ReadonlyArray; settings: ProjectGroupingSettings; groupScratchProjects?: boolean; + foldCoveredProjects?: boolean; primaryEnvironmentId: EnvironmentId | null; resolveEnvironmentLabel: (environmentId: EnvironmentId) => string | null; isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean; @@ -154,15 +162,7 @@ export function buildSidebarProjectSnapshots( }, resolve: MessageResolver = m, ): SidebarProjectSnapshot[] { - return buildProjectGroups( - { - projects: input.projects, - groupScratchProjects: input.groupScratchProjects ?? false, - settings: input.settings, - preferredEnvironmentId: input.primaryEnvironmentId, - }, - resolve, - ).map((group): SidebarProjectSnapshot => { + const toSnapshot = (group: ProjectGroup): SidebarProjectSnapshot => { const members = group.members.map( ({ physicalProjectKey, project }): SidebarProjectGroupMember => ({ ...project, @@ -210,11 +210,25 @@ export function buildSidebarProjectSnapshots( allRemoteMembersAreWsl, memberProjects: members, memberProjectRefs: group.memberProjectRefs, + folded: group.folded.map((folded) => ({ + ...toSnapshot(folded), + folderName: folded.folderName, + })), remoteEnvironmentLabels, pinned: group.pinned, archived: group.archived, }; - }); + }; + return buildProjectGroups( + { + projects: input.projects, + groupScratchProjects: input.groupScratchProjects ?? false, + foldCoveredProjects: input.foldCoveredProjects ?? false, + settings: input.settings, + preferredEnvironmentId: input.primaryEnvironmentId, + }, + resolve, + ).map(toSnapshot); } export function buildSidebarProjectPickerEntries(input: { diff --git a/docs/user/multi-repo-projects.md b/docs/user/multi-repo-projects.md index 7962770417175..bbb24bfc55706 100644 --- a/docs/user/multi-repo-projects.md +++ b/docs/user/multi-repo-projects.md @@ -55,9 +55,16 @@ thread's folder. A thread that changes one shows it as its own repository, with Git actions, while the repository that holds it shows the changed pin. A submodule never gets a worktree of its own, because its parent repository decides where it is checked out. +## In the sidebar + +If a repository the project covers has a project of its own, on this machine or on another +connected machine, the sidebar shows that project as part of this one, and lists this project's +threads together. See [Projects with several repositories](./thread-sidebar.md#projects-with-several-repositories). + ## Review changes -Each turn lists the files it changed, grouped by repository, and its diff covers all of them. See +Each turn lists the files it changed, grouped by repository, and its diff covers all of them. A +repository that has a project of its own shows that project's icon and name after its folder. See [Review turn changes](source-control.md#review-turn-changes). On web and desktop, the Diff pane's **Uncommitted**, **Changes**, and **Commits** sources read one diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 6c63f1b9c342d..245d267e0f3be 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -151,6 +151,25 @@ choice. While this is on, the active list is ordered by when each thread last came back to you, so you cannot drag or move threads within it. Your saved order returns when you turn it off. +### Projects with several repositories + +A project can [cover several repositories](./multi-repo-projects.md). When one of them also has +a project of its own, in the same folder on that machine or for the same repository on any +connected machine, that project shows in the sidebar as part of the project that covers it. Its +threads read `api · shop`: the repository, then the covering project. Filtering the sidebar to the +covering project shows them too. The project filter lists the repository's own project indented +under the covering project; pick it to see only that project's threads. It keeps its own settings. + +In the default sidebar, threads that show a status, such as Working, Input, or Done, come first. +Below them, each project that covers other repositories gathers its threads, and those of the +projects shown as part of it, under its name. A thread joins that group once it no longer shows a +status, for example after you open a Done thread. + +This is on by default. Turn it off with **Settings → General → Gather multi-repo projects** on web +and desktop to keep the active list in its usual order. Covered projects still show as part of the +project that covers them. Each device keeps its own choice. The project-grouped sidebar below puts +their threads in the covering project's folder. + ### Group threads by project (beta) Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active diff --git a/packages/client-runtime/src/state/projectGrouping.test.ts b/packages/client-runtime/src/state/projectGrouping.test.ts index 8f01ead8b9df1..ca34a5ae83d73 100644 --- a/packages/client-runtime/src/state/projectGrouping.test.ts +++ b/packages/client-runtime/src/state/projectGrouping.test.ts @@ -1,4 +1,6 @@ import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts"; +import { it as effectIt } from "@effect/vitest"; +import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; import type { EnvironmentProject } from "./models.ts"; @@ -8,6 +10,8 @@ import { deriveLogicalProjectKeyFromSettings, pickableProjectGroups, derivePhysicalProjectKey, + findCoveredFolderProject, + isCoveringProject, resolveGroupDefaultProject, resolveScratchProjectScopeKey, sortProjectsByGroupOrder, @@ -543,3 +547,171 @@ describe("sortProjectsByGroupOrder", () => { expect(sorted.map((entry) => entry.id)).toEqual(["pinned", "recent", "archived", "unlisted"]); }); }); + +describe("folding covered projects", () => { + const remote = EnvironmentId.make("remote"); + const identityOf = (name: string) => ({ + ...repositoryIdentity, + canonicalKey: `github.com/acme/${name}`, + locator: { ...repositoryIdentity.locator, remoteUrl: `https://github.com/acme/${name}.git` }, + name, + displayName: name, + }); + const shop = makeProject("shop", "/work/shop", { + repositoryIdentity: null, + trackedFolders: [ + { + path: "/work/shop/api", + name: "api", + discovered: true, + repositoryIdentity: identityOf("api"), + }, + { path: "/work/shop/web", name: "web", discovered: true }, + ], + }); + const api = makeProject("api", "/work/shop/api", { repositoryIdentity: identityOf("api") }); + const remoteApi = makeProject("api-remote", "/srv/api", { + environmentId: remote, + repositoryIdentity: identityOf("api"), + }); + const web = makeProject("web", "/work/shop/web", { repositoryIdentity: identityOf("web") }); + const other = makeProject("other", "/work/other", { repositoryIdentity: identityOf("other") }); + const fold = (projects: EnvironmentProject[], groupingSettings = settings("repository")) => + buildProjectGroups({ projects, settings: groupingSettings, foldCoveredProjects: true }); + const refOf = (project: EnvironmentProject) => ({ + environmentId: project.environmentId, + projectId: project.id, + }); + + it("folds the project in a covered folder, and the same repository on another environment", () => { + const groups = fold([shop, api, remoteApi, web, other]); + expect(groups.map((group) => group.label)).toEqual(["shop", "other"]); + const [shopGroup] = groups; + expect(shopGroup?.members.map((member) => member.project.id)).toEqual(["shop"]); + expect(shopGroup?.memberProjectRefs).toEqual([ + refOf(shop), + refOf(api), + refOf(remoteApi), + refOf(web), + ]); + expect(shopGroup?.folded.map(({ key, folderName }) => ({ key, folderName }))).toEqual([ + { key: "github.com/acme/api", folderName: "api" }, + { key: "github.com/acme/web", folderName: "web" }, + ]); + }); + + it("folds by folder only on the covering project's environment", () => { + const elsewhere = makeProject("web-remote", "/work/shop/web", { + environmentId: remote, + repositoryIdentity: null, + }); + expect(fold([shop, elsewhere]).map((group) => group.label)).toEqual(["shop", "web-remote"]); + }); + + it("leaves groups as they are unless asked, and keeps projects set to stay separate", () => { + expect( + buildProjectGroups({ projects: [shop, api], settings: settings("repository") }), + ).toHaveLength(2); + expect( + fold([shop, api], settings("repository", { [derivePhysicalProjectKey(api)]: "separate" })), + ).toHaveLength(2); + }); + + it("does not fold into an archived project", () => { + expect(fold([{ ...shop, archivedAt: "2026-07-02T00:00:00.000Z" }, api])).toHaveLength(2); + }); + + it("follows a chain of covering projects to its end, and keeps a cycle apart", () => { + const workspace = makeProject("workspace", "/work", { + repositoryIdentity: null, + trackedFolders: [{ path: "/work/shop", name: "shop" }], + }); + const groups = fold([workspace, shop, api]); + expect(groups.map((group) => group.label)).toEqual(["workspace"]); + expect(groups[0]?.folded.map((entry) => entry.folderName).toSorted()).toEqual(["api", "shop"]); + + const a = makeProject("a", "/a", { + repositoryIdentity: null, + trackedFolders: [{ path: "/b", name: "b" }], + }); + const b = makeProject("b", "/b", { + repositoryIdentity: null, + trackedFolders: [{ path: "/a", name: "a" }], + }); + expect(fold([a, b]).map((group) => group.label)).toEqual(["a", "b"]); + }); + + effectIt.prop( + "keeps every project in exactly one group and every group key once", + { + projects: Schema.Array( + Schema.Struct({ + remote: Schema.Boolean, + folder: Schema.Literals(["a", "b", "c", "d"]), + repository: Schema.NullOr(Schema.Literals(["x", "y"])), + covers: Schema.Array( + Schema.Struct({ + folder: Schema.Literals(["a", "b", "c", "d"]), + repository: Schema.NullOr(Schema.Literals(["x", "y"])), + }), + ), + archived: Schema.Boolean, + }), + ), + }, + ({ projects: specs }) => { + const projects = specs.map((spec, index) => + makeProject(`p${index}`, `/${spec.folder}`, { + ...(spec.remote ? { environmentId: remote } : {}), + repositoryIdentity: spec.repository === null ? null : identityOf(spec.repository), + trackedFolders: spec.covers.map((folder) => ({ + path: `/${folder.folder}`, + name: folder.folder, + ...(folder.repository === null + ? {} + : { repositoryIdentity: identityOf(folder.repository) }), + })), + ...(spec.archived ? { archivedAt: "2026-07-02T00:00:00.000Z" } : {}), + }), + ); + const plain = buildProjectGroups({ projects, settings: settings("repository") }); + const folded = fold(projects); + const refs = folded.flatMap((group) => + group.memberProjectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`), + ); + expect(refs.toSorted()).toEqual( + plain + .flatMap((group) => group.memberProjectRefs) + .map((ref) => `${ref.environmentId}:${ref.projectId}`) + .toSorted(), + ); + const keys = folded.flatMap((group) => [ + group.key, + ...group.folded.map((entry) => entry.key), + ]); + expect(keys.toSorted()).toEqual(plain.map((group) => group.key).toSorted()); + for (const group of folded) { + if (group.folded.length > 0) { + expect(group.archived).toBe(false); + expect(group.members.some(({ project }) => isCoveringProject(project))).toBe(true); + } + } + }, + ); +}); + +describe("findCoveredFolderProject", () => { + const remote = EnvironmentId.make("remote"); + it("prefers the project in the folder over another clone of its repository", () => { + const clone = makeProject("clone", "/clone", { environmentId: remote }); + const inFolder = makeProject("in-folder", "/work/t3code", { repositoryIdentity: null }); + const folder = { path: "/work/t3code", repositoryIdentity }; + expect(findCoveredFolderProject(folder, environmentId, [clone, inFolder])?.id).toBe( + "in-folder", + ); + expect(findCoveredFolderProject(folder, environmentId, [clone])?.id).toBe("clone"); + expect(findCoveredFolderProject({ path: "/work/t3code" }, environmentId, [clone])).toBe( + undefined, + ); + }); +}); diff --git a/packages/client-runtime/src/state/projectGrouping.ts b/packages/client-runtime/src/state/projectGrouping.ts index 164c1bea07d57..c9335b3d67ef1 100644 --- a/packages/client-runtime/src/state/projectGrouping.ts +++ b/packages/client-runtime/src/state/projectGrouping.ts @@ -3,6 +3,7 @@ import { repositoryGroupingDisplayNameOf, repositoryGroupingKeyOf, type EnvironmentId, + type ProjectTrackedFolder, type ScopedProjectRef, type SidebarProjectGroupingMode, } from "@t3tools/contracts"; @@ -280,6 +281,53 @@ export function deriveProjectGroupLabel(input: { return input.representative.title; } +type CoveredFolderCandidate = Pick< + EnvironmentProject, + "environmentId" | "workspaceRoot" | "repositoryIdentity" | "isScratch" +>; + +/** + * How `project` is a folder that a project on `environmentId` covers: the same folder on that + * environment, or the same repository on any environment. + */ +function coveredFolderMatch( + folder: Pick, + environmentId: EnvironmentId, + project: CoveredFolderCandidate, +): "folder" | "repository" | null { + if (project.isScratch) return null; + if ( + project.environmentId === environmentId && + normalizeProjectPathForComparison(project.workspaceRoot) === + normalizeProjectPathForComparison(folder.path) + ) { + return "folder"; + } + return folder.repositoryIdentity && + project.repositoryIdentity && + repositoryGroupingKeyOf(folder.repositoryIdentity) === + repositoryGroupingKeyOf(project.repositoryIdentity) + ? "repository" + : null; +} + +/** The project of a folder a project on `environmentId` covers, preferring the one in that folder. */ +export function findCoveredFolderProject( + folder: Pick, + environmentId: EnvironmentId, + projects: ReadonlyArray, +): TProject | undefined { + return ( + projects.find((project) => coveredFolderMatch(folder, environmentId, project) === "folder") ?? + projects.find((project) => coveredFolderMatch(folder, environmentId, project) === "repository") + ); +} + +/** A project covering other folders: the repositories inside it, or ones someone added. */ +export function isCoveringProject(project: Pick): boolean { + return (project.trackedFolders?.length ?? 0) > 0; +} + export interface ProjectGroupMember { readonly physicalProjectKey: string; readonly project: TProject; @@ -290,12 +338,21 @@ export interface ProjectGroup>; + /** Includes the projects of `folded` groups, whose threads show with this group's. */ readonly memberProjectRefs: ReadonlyArray; + /** Groups folded in because a project here covers their folder, with that folder's name. */ + readonly folded: ReadonlyArray>; /** Clients write every member together. When members still disagree, the project stays visible. */ readonly pinned: boolean; readonly archived: boolean; } +export interface FoldedProjectGroup< + TProject extends EnvironmentProject = EnvironmentProject, +> extends ProjectGroup { + readonly folderName: string; +} + /** The groups a project picker offers: archived groups left out, pinned ones first. */ export function pickableProjectGroups< TGroup extends { readonly pinned: boolean; readonly archived: boolean }, @@ -354,6 +411,8 @@ export function buildProjectGroups( readonly settings: ProjectGroupingSettings; readonly preferredEnvironmentId?: EnvironmentId | null; readonly groupScratchProjects?: boolean; + /** Fold each group whose folder another group's project covers into that group. */ + readonly foldCoveredProjects?: boolean; }, resolve: MFunctionType = mFallback, ): ReadonlyArray> { @@ -411,7 +470,7 @@ export function buildProjectGroups( } const preferredEnvironmentId = input.preferredEnvironmentId ?? null; - return Array.from(groupedMembers, ([key, members]) => { + const groups = Array.from(groupedMembers, ([key, members]): ProjectGroup => { const projects = members.map((member) => member.project); const representative = (preferredEnvironmentId @@ -434,10 +493,80 @@ export function buildProjectGroups( representative, members, memberProjectRefs: projectRefsByLogicalKey.get(key) ?? [], + folded: [], pinned: members.some((member) => member.project.pinnedAt != null), archived: !members.some(({ project }) => isPickableProjectMember(project)), }; }); + return input.foldCoveredProjects ? foldCoveredProjectGroups(groups, input.settings) : groups; +} + +/** + * Moves each group whose project is a folder another open group's project covers into that + * group, matching by folder before repository. A covered folder's project may cover folders + * itself, so a fold follows the chain to its end; groups covering each other stay apart. + */ +function foldCoveredProjectGroups( + groups: ReadonlyArray>, + settings: ProjectGroupingSettings, +): ReadonlyArray> { + const covered = groups.flatMap((group) => + group.archived + ? [] + : group.members.flatMap(({ project }) => + (project.trackedFolders ?? []).map((folder) => ({ group, project, folder })), + ), + ); + if (covered.length === 0) return groups; + const coveredBy = new Map, (typeof covered)[number]>(); + for (const group of groups) { + if (resolveProjectGroupingMode(group.representative, settings) === "separate") continue; + const find = (match: "folder" | "repository") => + covered.find( + (entry) => + entry.group !== group && + group.members.some( + ({ project }) => + coveredFolderMatch(entry.folder, entry.project.environmentId, project) === match, + ), + ); + const entry = find("folder") ?? find("repository"); + if (entry) coveredBy.set(group, entry); + } + const foldTarget = (group: ProjectGroup) => { + const seen = new Set([group]); + let target = coveredBy.get(group)?.group; + while (target !== undefined && coveredBy.has(target)) { + if (seen.has(target)) return undefined; + seen.add(target); + target = coveredBy.get(target)!.group; + } + return target; + }; + const foldedInto = new Map, FoldedProjectGroup[]>(); + for (const [group, entry] of coveredBy) { + const target = foldTarget(group); + if (target === undefined) continue; + const folded = foldedInto.get(target) ?? []; + folded.push({ ...group, folderName: entry.folder.name }); + foldedInto.set(target, folded); + } + return groups.flatMap((group) => { + if (foldTarget(group) !== undefined) return []; + const folded = foldedInto.get(group); + return folded === undefined + ? [group] + : [ + { + ...group, + memberProjectRefs: [ + ...group.memberProjectRefs, + ...folded.flatMap((entry) => entry.memberProjectRefs), + ], + folded, + }, + ]; + }); } export function sortProjectsByGroupOrder< diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index f98a14c3ed32d..0680031334714 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -257,6 +257,34 @@ describe("applyShellStreamEvent", () => { expect(next.projects[0]?.repositoryIdentity).toEqual(liveIdentity); }); + it("takes tracked folder identities from a refresh and keeps them through later deltas", () => { + const folder = { path: "/work/shop/api", name: "api", discovered: true }; + const shop = { ...v2Project, trackedFolders: [folder] }; + const start = { ...v2ShellSnapshot, snapshotSequence: 5, projects: [shop] }; + const refreshed = mergeShellSnapshotProjects( + start, + { + ...start, + snapshotSequence: 4, + projects: [{ ...shop, trackedFolders: [{ ...folder, repositoryIdentity }] }], + }, + { resolvedRepositoryIdentityRoots: [folder.path] }, + ); + expect(refreshed.projects[0]?.trackedFolders).toEqual([{ ...folder, repositoryIdentity }]); + expect( + mergeShellSnapshotProjects(refreshed, refreshed, { + resolvedRepositoryIdentityRoots: [folder.path], + }), + ).toBe(refreshed); + + const renamed = applyShellStreamEvent(refreshed, { + kind: "project.updated", + sequence: 6, + project: { ...shop, title: "Shop" }, + }); + expect(renamed.projects[0]?.trackedFolders).toEqual([{ ...folder, repositoryIdentity }]); + }); + it("keeps archive deltas out of the normal shell cache", () => { const archived = applyShellStreamEvent(v2ShellSnapshot, { kind: "thread.updated", diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index 2ef7dea533f3c..31585f7f222dc 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -1,6 +1,7 @@ import { OrchestrationProjectShell, OrchestrationV2ThreadShell, + ProjectTrackedFolders, RepositoryIdentity, ThreadPullRequestLink, type OrchestrationV2ShellSnapshot, @@ -14,6 +15,7 @@ const sameLinks = Schema.toEquivalence(Schema.UndefinedOr(Schema.Array(ThreadPul const sameRepositoryIdentity = Schema.toEquivalence( Schema.UndefinedOr(Schema.NullOr(RepositoryIdentity)), ); +const sameTrackedFolders = Schema.toEquivalence(Schema.UndefinedOr(ProjectTrackedFolders)); export function sameThreadPullRequests( left: OrchestrationV2ThreadShell["pullRequests"], @@ -60,14 +62,30 @@ function retainRepositoryIdentity( previous: OrchestrationProjectShell | undefined, next: OrchestrationProjectShell, ): OrchestrationProjectShell { + let merged = next; if ( next.repositoryIdentity == null && previous?.repositoryIdentity != null && previous.workspaceRoot === next.workspaceRoot ) { - return { ...next, repositoryIdentity: previous.repositoryIdentity }; + merged = { ...merged, repositoryIdentity: previous.repositoryIdentity }; } - return next; + // Tracked folders' identities resolve the same way, so a folder keeps the one it had. + const known = new Map( + previous?.trackedFolders?.flatMap((folder) => + folder.repositoryIdentity ? [[folder.path, folder.repositoryIdentity] as const] : [], + ), + ); + if (known.size > 0 && next.trackedFolders?.some((folder) => !folder.repositoryIdentity)) { + merged = { + ...merged, + trackedFolders: next.trackedFolders.map((folder) => { + const repositoryIdentity = folder.repositoryIdentity ?? known.get(folder.path); + return repositoryIdentity ? { ...folder, repositoryIdentity } : folder; + }), + }; + } + return merged; } export interface MergeShellSnapshotOptions { @@ -98,18 +116,25 @@ export function mergeShellSnapshotProjects( if (candidate === undefined || candidate.workspaceRoot !== project.workspaceRoot) { return project; } + let merged = project; if (resolvedRootSet?.has(project.workspaceRoot) === true) { // Refreshes re-resolve every root; an unchanged identity keeps the project's identity // so every subscriber (each pull request row, the sidebar) skips re-rendering. - if (sameRepositoryIdentity(project.repositoryIdentity, candidate.repositoryIdentity)) { - return project; + if (!sameRepositoryIdentity(project.repositoryIdentity, candidate.repositoryIdentity)) { + merged = { ...merged, repositoryIdentity: candidate.repositoryIdentity }; } - return { ...project, repositoryIdentity: candidate.repositoryIdentity }; + } else if (project.repositoryIdentity == null && candidate.repositoryIdentity != null) { + merged = { ...merged, repositoryIdentity: candidate.repositoryIdentity }; } - if (project.repositoryIdentity == null && candidate.repositoryIdentity != null) { - return { ...project, repositoryIdentity: candidate.repositoryIdentity }; + // A refresh also carries identities resolved for the project's tracked folders. + const { trackedFolders } = retainRepositoryIdentity(project, candidate); + if ( + trackedFolders !== undefined && + !sameTrackedFolders(project.trackedFolders, trackedFolders) + ) { + merged = { ...merged, trackedFolders }; } - return project; + return merged; }); return projects.every((project, index) => project === previous.projects[index]) ? previous diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 0077ef78020d8..487174b978f1b 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -61,12 +61,17 @@ export const ProjectTrackedFolder = Schema.Struct({ * the disk. Absent on a folder someone added. */ discovered: Schema.optional(Schema.Boolean), + /** + * The repository at this folder, when the server has resolved it. Filled in on project shells + * and never stored; clients match projects for the same repository on other environments by it. + */ + repositoryIdentity: Schema.optional(RepositoryIdentity), }); export type ProjectTrackedFolder = typeof ProjectTrackedFolder.Type; /** The folders a caller adds to a project. Which repositories sit inside it is the server's to say. */ export const ProjectAddedFolders = Schema.Array( - ProjectTrackedFolder.mapFields(Struct.omit(["discovered"])), + ProjectTrackedFolder.mapFields(Struct.omit(["discovered", "repositoryIdentity"])), ).check(Schema.isMaxLength(PROJECT_TRACKED_FOLDERS_MAX)); export const ProjectTrackedFolders = Schema.Array(ProjectTrackedFolder).check( diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e7887f88f0369..8e1f2a2ea0961 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -556,6 +556,10 @@ export const ClientSettingsSchema = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed({})), ), sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + // Status threads lead; each multi-repository project's threads gather under its name below them. + sidebarGatherProjectThreads: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(true)), + ), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)), ), @@ -2133,6 +2137,7 @@ export const ClientSettingsPatch = Schema.Struct({ threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), + sidebarGatherProjectThreads: Schema.optionalKey(Schema.Boolean), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), sidebarProjectGroupingOverrides: Schema.optionalKey( Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),