From c2d813cf0e87b2be248e480c0fc80afede50d08c Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:50:44 -0800 Subject: [PATCH 01/26] feat(projects): a project can track several repositories A project was one folder, so a wrapper folder holding several repositories showed "no changes" and agents had no grant for sibling repositories. A project now stores a list of tracked folders next to its own folder. Adding a folder scans one level down and reads a .code-workspace file, then offers a checklist; Settings > Projects has Rescan, Add folder and Remove. Agents get the folders as writable roots where the provider supports it and a short folder list in their instructions. Co-Authored-By: Claude Fable 5.2 --- .../projects/AddProjectScreen.test.ts | 69 ++- .../features/projects/AddProjectScreen.tsx | 126 +++++- .../features/projects/ScannedFolderRows.tsx | 34 ++ .../settings/ProjectRepositoriesSection.tsx | 228 ++++++++++ .../SettingsProjectOverviewRouteScreen.tsx | 15 + apps/server/src/auth/RpcAuthorization.ts | 2 + apps/server/src/cli/project.test.ts | 53 ++- apps/server/src/cli/project.ts | 32 +- .../src/mcp/toolkits/project/handlers.test.ts | 11 +- .../src/mcp/toolkits/project/handlers.ts | 1 + .../src/observability/RpcInstrumentation.ts | 2 + .../Adapters/ClaudeAdapterV2.test.ts | 36 +- .../Adapters/ClaudeAdapterV2.ts | 20 +- .../Adapters/CodexAdapterV2.test.ts | 31 ++ .../Adapters/CodexAdapterV2.ts | 25 +- .../Adapters/GrokAdapterV2.test.ts | 6 + .../orchestration-v2/ProjectCommands.test.ts | 32 ++ .../src/orchestration-v2/ProjectCommands.ts | 9 + .../src/orchestration-v2/ProjectStore.test.ts | 14 +- .../src/orchestration-v2/ProjectStore.ts | 10 + .../orchestration-v2/RuntimePolicy.test.ts | 29 ++ .../src/orchestration-v2/RuntimePolicy.ts | 17 + .../ThreadLaunchService.test.ts | 2 + .../ThreadTitleRegenerationService.test.ts | 1 + .../src/orchestration-v2/runtimeLayer.ts | 2 + apps/server/src/persistence/Migrations.ts | 2 + .../092_ProjectionProjectsTrackedFolders.ts | 15 + .../reconcileV2PreviewMigration.test.ts | 2 + apps/server/src/project/ProjectMutation.ts | 6 + .../server/src/project/ProjectService.test.ts | 65 ++- apps/server/src/project/ProjectService.ts | 49 +++ .../provider/acp/AcpJsonRpcConnection.test.ts | 6 +- .../src/provider/agentContextBudget.json | 2 +- apps/server/src/server.ts | 2 + .../src/workspace/WorkspaceFolders.test.ts | 173 ++++++++ apps/server/src/workspace/WorkspaceFolders.ts | 280 ++++++++++++ apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 4 + ...ommandPalette.composition.browser.test.tsx | 3 +- apps/web/src/components/CommandPalette.tsx | 256 ++++++----- .../TrackedFoldersDialog.logic.test.ts | 115 +++++ .../components/TrackedFoldersDialog.logic.ts | 101 +++++ .../src/components/TrackedFoldersDialog.tsx | 183 ++++++++ .../settings/ProjectRepositoriesSettings.tsx | 397 ++++++++++++++++++ .../settings/ProjectSettingsPanel.tsx | 2 + .../src/components/settings/settingsSearch.ts | 6 + docs/user/project-settings.md | 18 + .../client-runtime/src/operations/commands.ts | 8 + .../client-runtime/src/operations/projects.ts | 5 + .../client-runtime/src/state/filesystem.ts | 12 + .../src/state/projectTrackedFolders.test.ts | 77 ++++ .../src/state/projectTrackedFolders.ts | 51 +++ packages/client-runtime/src/state/projects.ts | 1 + packages/contracts/src/applicationEvent.ts | 4 +- packages/contracts/src/index.ts | 1 + .../contracts/src/orchestrationProject.ts | 4 +- packages/contracts/src/project.ts | 24 ++ packages/contracts/src/rpc.ts | 23 + packages/contracts/src/workspaceFolders.ts | 62 +++ .../src/server/AcpSessionRuntime.ts | 12 +- packages/provider-acp/src/server/adapter.ts | 5 + .../src/server/clientPolicy.test.ts | 10 + .../provider-acp/src/server/clientPolicy.ts | 20 +- .../src/server/ProviderAdapter.ts | 15 + .../src/server/runtimeInstructions.test.ts | 71 +++- .../src/server/runtimeInstructions.ts | 69 ++- .../provider-cursor/src/server/adapter.ts | 5 +- .../provider-muse/src/server/adapter.test.ts | 6 +- packages/provider-muse/src/server/adapter.ts | 9 +- .../src/server/adapter.test.ts | 18 + .../provider-opencode/src/server/adapter.ts | 15 +- .../src/server/v2/adapter.ts | 14 +- 72 files changed, 2855 insertions(+), 182 deletions(-) create mode 100644 apps/mobile/src/features/projects/ScannedFolderRows.tsx create mode 100644 apps/mobile/src/features/settings/ProjectRepositoriesSection.tsx create mode 100644 apps/server/src/persistence/Migrations/092_ProjectionProjectsTrackedFolders.ts create mode 100644 apps/server/src/workspace/WorkspaceFolders.test.ts create mode 100644 apps/server/src/workspace/WorkspaceFolders.ts create mode 100644 apps/web/src/components/TrackedFoldersDialog.logic.test.ts create mode 100644 apps/web/src/components/TrackedFoldersDialog.logic.ts create mode 100644 apps/web/src/components/TrackedFoldersDialog.tsx create mode 100644 apps/web/src/components/settings/ProjectRepositoriesSettings.tsx create mode 100644 packages/client-runtime/src/state/projectTrackedFolders.test.ts create mode 100644 packages/client-runtime/src/state/projectTrackedFolders.ts create mode 100644 packages/contracts/src/workspaceFolders.ts diff --git a/apps/mobile/src/features/projects/AddProjectScreen.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.test.ts index 4718133f7a5a5..2b5aa2aa97dcc 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.test.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.test.ts @@ -21,6 +21,8 @@ const state = vi.hoisted(() => ({ scopes: new Set(), baseDirectory: "", projects: [] as string[], + trackedFolders: [] as unknown[], + scanResult: null as unknown, existingProjects: [] as { environmentId: string; id: string; @@ -30,6 +32,7 @@ const state = vi.hoisted(() => ({ }[], cloneDestinations: [] as string[], createResult: null as Promise | null, + createSent: null as (() => void) | null, createNewResult: null as Promise | null, startCloneResult: null as Promise | null, connectionStates: {} as Record, @@ -140,14 +143,17 @@ vi.mock("../../state/use-remote-environment-registry", () => ({ }), })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); -// Only filesystem.browse of `~` answers, with the host's home as its parentPath. +// filesystem.browse of `~` answers with the host's home as its parentPath; a scan answers scanResult. vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => - async ({ input }: { input?: { partialPath?: string } }) => - input?.partialPath === "~" - ? AsyncResult.success({ parentPath: "/home/tester", entries: [] }) - : undefined, + async ({ input }: { input?: { partialPath?: string; workspaceRoot?: string } }) => { + if (input?.partialPath === "~") { + return AsyncResult.success({ parentPath: "/home/tester", entries: [] }); + } + if (input?.workspaceRoot === undefined) return undefined; + return state.scanResult ?? AsyncResult.failure(Cause.fail(new Error("Scan failed"))); + }, })); vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) })); vi.mock("../../state/presentation", () => ({ @@ -168,13 +174,15 @@ vi.mock("../../state/sourceControl", () => ({ vi.mock("../../state/projects", () => ({ projectEnvironment: { createNew: () => state.createNewResult, - create: ({ input }: { input: { workspaceRoot: string } }) => { + create: ({ input }: { input: { workspaceRoot: string; trackedFolders?: unknown } }) => { if (!state.scopes.has(AuthOrchestrationOperateScope)) { return Promise.resolve( AsyncResult.failure(Cause.fail(new Error("Project creation denied"))), ); } state.projects.push(input.workspaceRoot); + state.trackedFolders.push(input.trackedFolders); + state.createSent?.(); return state.createResult ?? Promise.resolve(AsyncResult.success(undefined)); }, }, @@ -540,19 +548,23 @@ describe("local project navigation", () => { state.scopes = new Set([AuthOrchestrationOperateScope]); state.baseDirectory = baseDirectory; state.projects = []; + state.trackedFolders = []; + state.scanResult = null; state.dispatch.mockReset(); state.alert.mockReset(); state.waitForProject.mockReset(); const created = Promise.withResolvers>>(); const projected = Promise.withResolvers(); + const sent = Promise.withResolvers(); state.createResult = created.promise; + state.createSent = sent.resolve; state.waitForProject.mockReturnValue(projected.promise); const submit = findAction( renderScreen(() => AddProjectLocalFolderScreen({ environmentId: "environment" })), "Add project", ); if (!submit) throw new Error("Add project action missing"); - return { created, projected, submit }; + return { created, projected, sent: sent.promise, submit }; } it("keeps navigation in place and explains a project projection timeout", async () => { @@ -592,6 +604,45 @@ describe("local project navigation", () => { } }); + it("offers the repositories a scan finds before adding the project", async () => { + const { created, projected } = setup(); + state.scanResult = AsyncResult.success({ + workspaceRoot: "/tmp/t3-mobile-audit-fixture", + isGitRepository: false, + codeWorkspaceFile: null, + folders: ["api", "web"].map((name) => ({ + path: `/tmp/t3-mobile-audit-fixture/${name}`, + name, + isGitRepository: true, + source: "child", + })), + }); + created.resolve(AsyncResult.success(undefined)); + projected.resolve(null); + const root = createRoot(document.createElement("div")); + mountedRoots.push(root); + let screen: ReactNode; + function Observer() { + screen = AddProjectLocalFolderScreen({ environmentId: "environment" }); + return null; + } + await act(() => root.render(createElement(Observer))); + await act(() => findAction(screen, "Add project")?.()); + + state.scanResult = null; + + expect(state.projects).toEqual([]); + await act(() => findAction(screen, "Add with 2 repositories")?.()); + + expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]); + expect(state.trackedFolders).toEqual([ + [ + { path: "/tmp/t3-mobile-audit-fixture/api", name: "api" }, + { path: "/tmp/t3-mobile-audit-fixture/web", name: "web" }, + ], + ]); + }); + it("does not replace a reopened flow when the previous submission finishes", async () => { const { created, projected, submit } = setup(); const navigation = mountProjectFlow(false); @@ -701,12 +752,12 @@ describe("local project navigation", () => { ])( "waits for projection then selects the draft from $origin", async ({ withDraft, withChooser }) => { - const { created, projected, submit } = setup(); + const { created, projected, sent, submit } = setup(); const navigation = mountProjectFlow(withDraft, withChooser, true); const before = navigation.getState(); const submission = submit(); created.resolve(AsyncResult.success(undefined)); - await created.promise; + await sent; expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]); expect(navigation.getState()).toBe(before); projected.resolve({ environmentId: "environment", id: "project" }); diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 56518cd071eac..bc61831699a57 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -48,6 +48,7 @@ import { appendBrowsePathSegment, inferProjectTitleFromPath, isWindowsPlatform, + trackedFoldersFromSelection, } from "@t3tools/client-runtime/state/projects"; import { resolvePastedPath } from "@t3tools/shared/path"; import { @@ -58,8 +59,10 @@ import { type EnvironmentId, type EnvironmentMachineKind, ProjectId, + type ProjectTrackedFolder, resolveEnvironmentMachineKind, SourceControlProviderKind, + type WorkspaceScannedFolder, } from "@t3tools/contracts"; import { StackActions, @@ -86,6 +89,7 @@ import { sourceControlEnvironment } from "../../state/sourceControl"; import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol"; import { ErrorBanner } from "../../components/ui/ErrorBanner"; +import { ScannedFolderRows, scannedFolderCountLabel } from "./ScannedFolderRows"; import { SourceControlIcon } from "./SourceControlIcon"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { ThemedSwitch } from "../../components/ui/ThemedSwitch"; @@ -811,11 +815,22 @@ function useOpenExistingProject(environment: EnvironmentOption | null) { function useCreateProject(environment: EnvironmentOption | null) { const openNewTaskDraft = useOpenNewTaskDraft(); const navigation = useNavigation(); - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const sendCreateProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const openExistingProject = useOpenExistingProject(environment); + const projects = useProjects(); - return async ( + const findExisting = (lookupPath: string) => + environment + ? findExistingAddProject({ + projects, + environmentId: environment.environmentId, + path: lookupPath, + }) + : null; + + const createProject = async ( workspaceRoot: string, + trackedFolders: ReadonlyArray = [], originRoute = getActiveRoute(navigation), lookupPath = workspaceRoot, ) => { @@ -840,8 +855,9 @@ function useCreateProject(environment: EnvironmentOption | null) { commandId: CommandId.make(uuidv4()), projectId, workspaceRoot, + trackedFolders, }); - const result = await createProject({ + const result = await sendCreateProject({ environmentId: environment.environmentId, input: command, }); @@ -871,6 +887,8 @@ function useCreateProject(environment: EnvironmentOption | null) { ); return result; }; + + return { createProject, findExisting }; } function useEnvironmentFromParam( @@ -1367,11 +1385,37 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st AuthOrchestrationOperateScope, ); const navigation = useNavigation(); - const createProject = useCreateProject(environment); + const { createProject, findExisting } = useCreateProject(environment); + const scanFolders = useAtomQueryRunner(filesystemEnvironment.scanFolders, { + reportFailure: false, + reportDefect: false, + refresh: true, + }); const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = useBrowsePathInput(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); + const [found, setFound] = useState<{ + readonly workspaceRoot: string; + readonly lookupPath: string; + readonly folders: ReadonlyArray; + } | null>(null); + const [deselectedPaths, setDeselectedPaths] = useState>(new Set()); + + const addProject = async ( + workspaceRoot: string, + trackedFolders: ReadonlyArray, + originRoute: ReturnType, + lookupPath: string, + ) => { + setError(null); + setIsSubmitting(true); + const result = await createProject(workspaceRoot, trackedFolders, originRoute, lookupPath); + if (result && AsyncResult.isFailure(result)) { + setError(errorMessage(Cause.squash(result.cause))); + } + setIsSubmitting(false); + }; const submitPath = async () => { if (!environment || isBrowseNavigating || isSubmitting) return; @@ -1391,13 +1435,79 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st const lookupPath = resolved.path.startsWith("~") ? await resolveHomePath(resolved.path) : resolved.path; - const result = await createProject(resolved.path, originRoute, lookupPath); - if (result && AsyncResult.isFailure(result)) { - setError(errorMessage(Cause.squash(result.cause))); + if (!findExisting(lookupPath)) { + // A scan that fails, or an environment too old to scan, adds the folder alone. + const scan = await scanFolders({ + environmentId: environment.environmentId, + input: { workspaceRoot: resolved.path }, + }); + if (AsyncResult.isSuccess(scan) && scan.value.folders.length > 0) { + setDeselectedPaths(new Set()); + setFound({ workspaceRoot: resolved.path, lookupPath, folders: scan.value.folders }); + setIsSubmitting(false); + return; + } } - setIsSubmitting(false); + await addProject(resolved.path, [], originRoute, lookupPath); }; + if (environment && found) { + const selected = trackedFoldersFromSelection(found.folders, deselectedPaths); + const selectedFolders = found.folders.filter((folder) => !deselectedPaths.has(folder.path)); + return ( + + {error ? : null} + + {`Found ${scannedFolderCountLabel(found.folders)} in ${found.workspaceRoot}. Agents in this project can work in the ones you keep selected.`} + + 0 + ? `Add with ${scannedFolderCountLabel(selectedFolders)}` + : "Add with repositories" + } + disabled={!canCreateProject || isSubmitting || selected.length === 0} + onPress={() => + void addProject( + found.workspaceRoot, + selected, + getActiveRoute(navigation), + found.lookupPath, + ) + } + loading={isSubmitting} + /> + + ), + } : isBrowsing - ? browseInputEndPaddingClass({ - willCreateProjectPath, - hasHighlightedBrowseItem, - }) - : undefined, - placeholder: inputPlaceholder, - "aria-describedby": inputAccessory ? submitButtonId : undefined, - ...(isSubmenu - ? { - startAddon: ( - - ), + ? { startAddon: } + : {}), + onKeyDown: handleKeyDown, + }} + mode="none" + items={resultRows.itemValues} + virtualized + onItemHighlighted={(value, eventDetails) => { + if (eventDetails.reason === "none" && highlightClearedRef.current) return; + highlightClearedRef.current = false; + setHighlightedItemValue(typeof value === "string" ? value : null); + const rowIndex = resultRows.rowIndexByItemIndex[eventDetails.index]; + if (eventDetails.reason === "keyboard" && rowIndex !== undefined) { + scrollCommandPaletteRowIntoView( + resultListRef.current, + rowIndex, + eventDetails.index === 0, + ); + } + }} + onValueChange={(nextQuery, { event }) => handleQueryChange(nextQuery, event.target)} + pendingSelectionRef={remountSelectionRef} + showBackHint={isSubmenu} + value={query} + > + {newProjectPathPreview !== null ? ( + + ) : null} + {addProjectCloneFlow?.step === "confirm" ? ( + } - : {}), - onKeyDown: handleKeyDown, - }} - mode="none" - items={resultRows.itemValues} - virtualized - onItemHighlighted={(value, eventDetails) => { - if (eventDetails.reason === "none" && highlightClearedRef.current) return; - highlightClearedRef.current = false; - setHighlightedItemValue(typeof value === "string" ? value : null); - const rowIndex = resultRows.rowIndexByItemIndex[eventDetails.index]; - if (eventDetails.reason === "keyboard" && rowIndex !== undefined) { - scrollCommandPaletteRowIntoView( - resultListRef.current, - rowIndex, - eventDetails.index === 0, - ); - } - }} - onValueChange={(nextQuery, { event }) => handleQueryChange(nextQuery, event.target)} - pendingSelectionRef={remountSelectionRef} - showBackHint={isSubmenu} - value={query} - > - {newProjectPathPreview !== null ? ( - + ) : null} + {browseAccessError ? ( +
+ {browseAccessError} +
+ ) : isBrowsePending && browseResult === null ? ( +
+ Loading folders... +
+ ) : null} + - ) : null} - {addProjectCloneFlow?.step === "confirm" ? ( - + {trackedFoldersRequest ? ( + + trackedFoldersRequest.resolve(checked.map(({ path, name }) => ({ path, name }))) } - description={addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl} + onSkip={() => trackedFoldersRequest.resolve([])} + onClose={() => trackedFoldersRequest.resolve(null)} /> ) : null} - {browseAccessError ? ( -
- {browseAccessError} -
- ) : isBrowsePending && browseResult === null ? ( -
- Loading folders... -
- ) : null} - - + ); } diff --git a/apps/web/src/components/TrackedFoldersDialog.logic.test.ts b/apps/web/src/components/TrackedFoldersDialog.logic.test.ts new file mode 100644 index 0000000000000..9f27f010ba743 --- /dev/null +++ b/apps/web/src/components/TrackedFoldersDialog.logic.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + filterScannedFolders, + mergeScannedTrackedFolders, + resolveTrackedFolderInput, + trackedFolderDisplayPath, + untrackedScannedPaths, +} from "./TrackedFoldersDialog.logic"; + +const scanned = (path: string, name: string) => ({ + path, + name, + isGitRepository: true, + source: "child" as const, +}); + +describe("trackedFolderDisplayPath", () => { + it.each([ + ["/work/app/api", "/work/app", "api"], + ["/work/app/packages/web", "/work/app/", "packages/web"], + ["/work/other", "/work/app", "/work/other"], + ["/work/app-two", "/work/app", "/work/app-two"], + ["C:\\Work\\App\\api", "c:\\work\\app", "api"], + ])("shows %s under %s as %s", (path, root, expected) => { + expect(trackedFolderDisplayPath(path, root)).toBe(expected); + }); +}); + +describe("mergeScannedTrackedFolders", () => { + const api = scanned("/work/app/api", "api"); + const web = scanned("/work/app/web", "web"); + const docs = scanned("/work/app/docs", "docs"); + + it("keeps tracked folders the scan did not return and appends newly checked ones", () => { + expect( + mergeScannedTrackedFolders({ + tracked: [ + { path: "/elsewhere/shared", name: "shared" }, + { path: "/work/app/api", name: "API service" }, + { path: "/work/app/web", name: "web" }, + ], + scanned: [api, web, docs], + checked: [api, docs], + }), + ).toEqual([ + { path: "/elsewhere/shared", name: "shared" }, + { path: "/work/app/api", name: "API service" }, + { path: "/work/app/docs", name: "docs" }, + ]); + }); + + it("matches Windows paths without regard to case or separator", () => { + const windowsApi = scanned("C:\\Work\\App\\api", "api"); + expect( + mergeScannedTrackedFolders({ + tracked: [{ path: "c:/work/app/api", name: "api" }], + scanned: [windowsApi], + checked: [windowsApi], + }), + ).toEqual([{ path: "c:/work/app/api", name: "api" }]); + }); +}); + +describe("untrackedScannedPaths", () => { + it("returns the scanned paths that are not tracked yet", () => { + expect([ + ...untrackedScannedPaths( + [{ path: "/work/app/api", name: "api" }], + [scanned("/work/app/api", "api"), scanned("/work/app/web", "web")], + ), + ]).toEqual(["/work/app/web"]); + }); +}); + +describe("filterScannedFolders", () => { + it("matches the name or the path, ignoring case", () => { + const folders = [scanned("/work/app/api", "API"), scanned("/work/libs/web", "web")]; + expect(filterScannedFolders(folders, " api ")).toEqual([folders[0]]); + expect(filterScannedFolders(folders, "LIBS")).toEqual([folders[1]]); + expect(filterScannedFolders(folders, "")).toBe(folders); + }); +}); + +describe("resolveTrackedFolderInput", () => { + it.each([ + [ + "an absolute path that is not listed", + { query: "/srv/repos/tools/", listedDirectoryPath: null, exactEntryPath: null }, + { path: "/srv/repos/tools", name: "tools" }, + ], + [ + "a listed directory, which resolves the home prefix", + { query: "~/code/", listedDirectoryPath: "/home/me/code", exactEntryPath: null }, + { path: "/home/me/code", name: "code" }, + ], + [ + "an exact entry of the listed directory", + { + query: "~/code/tools", + listedDirectoryPath: "/home/me/code", + exactEntryPath: "/home/me/code/tools", + }, + { path: "/home/me/code/tools", name: "tools" }, + ], + ])("resolves %s", (_label, input, expected) => { + expect(resolveTrackedFolderInput(input)).toEqual(expected); + }); + + it.each(["", " ", "~/code/too", "relative/path"])("rejects %j without a listing", (query) => { + expect( + resolveTrackedFolderInput({ query, listedDirectoryPath: null, exactEntryPath: null }), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/components/TrackedFoldersDialog.logic.ts b/apps/web/src/components/TrackedFoldersDialog.logic.ts new file mode 100644 index 0000000000000..90021a3898815 --- /dev/null +++ b/apps/web/src/components/TrackedFoldersDialog.logic.ts @@ -0,0 +1,101 @@ +import type { ProjectTrackedFolder, WorkspaceScannedFolder } from "@t3tools/contracts"; +import { hasTrailingPathSeparator } from "@t3tools/client-runtime/state/projects"; +import { + fileBasename, + isAbsolutePath, + normalizeProjectPathForComparison, + normalizeProjectPathForDispatch, + workspaceRelativeFilePath, +} from "@t3tools/shared/path"; + +export const TRACKED_FOLDERS_FILTER_THRESHOLD = 8; + +/** Relative to the project folder when inside it, absolute otherwise. */ +export function trackedFolderDisplayPath(path: string, workspaceRoot: string): string { + const relative = workspaceRelativeFilePath(path, workspaceRoot); + return relative === null || relative === "." ? path : relative; +} + +export function filterScannedFolders( + folders: ReadonlyArray, + query: string, +): ReadonlyArray { + const needle = query.trim().toLowerCase(); + if (needle.length === 0) return folders; + return folders.filter( + (folder) => + folder.name.toLowerCase().includes(needle) || folder.path.toLowerCase().includes(needle), + ); +} + +/** Scanned paths that the project does not track yet. */ +export function untrackedScannedPaths( + tracked: ReadonlyArray, + scanned: ReadonlyArray, +): ReadonlySet { + const trackedKeys = new Set( + tracked.map((folder) => normalizeProjectPathForComparison(folder.path)), + ); + return new Set( + scanned + .filter((folder) => !trackedKeys.has(normalizeProjectPathForComparison(folder.path))) + .map((folder) => folder.path), + ); +} + +/** + * The tracked list after a rescan. A tracked folder the scan did not return stays, since it was + * added by path or is missing right now; one the scan returned stays only while it is checked. + */ +export function mergeScannedTrackedFolders(input: { + readonly tracked: ReadonlyArray; + readonly scanned: ReadonlyArray; + readonly checked: ReadonlyArray; +}): ReadonlyArray { + const scannedKeys = new Set( + input.scanned.map((folder) => normalizeProjectPathForComparison(folder.path)), + ); + const checkedKeys = new Set( + input.checked.map((folder) => normalizeProjectPathForComparison(folder.path)), + ); + const seen = new Set(); + const merged: ProjectTrackedFolder[] = []; + for (const folder of input.tracked) { + const key = normalizeProjectPathForComparison(folder.path); + if (seen.has(key) || (scannedKeys.has(key) && !checkedKeys.has(key))) continue; + seen.add(key); + merged.push(folder); + } + for (const folder of input.checked) { + const key = normalizeProjectPathForComparison(folder.path); + if (seen.has(key)) continue; + seen.add(key); + merged.push({ path: folder.path, name: folder.name }); + } + return merged; +} + +/** + * The folder a typed path adds. A listing resolves `~/` and names the directory exactly; without + * one, only an absolute path is safe to send. + */ +export function resolveTrackedFolderInput(input: { + readonly query: string; + readonly listedDirectoryPath: string | null; + readonly exactEntryPath: string | null; +}): ProjectTrackedFolder | null { + const query = input.query.trim(); + if (query.length === 0) return null; + const rawPath = + input.exactEntryPath ?? + (hasTrailingPathSeparator(query) && input.listedDirectoryPath !== null + ? input.listedDirectoryPath + : isAbsolutePath(query) + ? query + : null); + if (rawPath === null) return null; + const path = normalizeProjectPathForDispatch(rawPath); + const name = fileBasename(path).trim(); + if (path.length === 0 || name.length === 0) return null; + return { path, name }; +} diff --git a/apps/web/src/components/TrackedFoldersDialog.tsx b/apps/web/src/components/TrackedFoldersDialog.tsx new file mode 100644 index 0000000000000..af9686140cb9d --- /dev/null +++ b/apps/web/src/components/TrackedFoldersDialog.tsx @@ -0,0 +1,183 @@ +import { + PROJECT_TRACKED_FOLDERS_MAX, + type WorkspaceScanFoldersResult, + type WorkspaceScannedFolder, +} from "@t3tools/contracts"; +import { fileBasename } from "@t3tools/shared/path"; +import { useState } from "react"; + +import { + filterScannedFolders, + TRACKED_FOLDERS_FILTER_THRESHOLD, + trackedFolderDisplayPath, +} from "./TrackedFoldersDialog.logic"; +import { Badge } from "./ui/badge"; +import { Button } from "./ui/button"; +import { CheckboxMark } from "./ui/checkbox"; +import { + Dialog, + DialogAction, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "./ui/dialog"; +import { Input } from "./ui/input"; + +const NO_NEW_PATHS: ReadonlySet = new Set(); + +/** + * Mount it only while it is open. `add` offers the folders found for a new project, with a way to + * add the project without any; `edit` confirms a rescan of an existing one. + */ +export function TrackedFoldersDialog(props: { + readonly mode: "add" | "edit"; + readonly scan: WorkspaceScanFoldersResult; + /** How many of the listed folders may be checked before the project's limit is reached. */ + readonly maxChecked: number; + /** Listed paths the project does not track yet, marked in `edit` mode. */ + readonly newPaths?: ReadonlySet; + readonly busy?: boolean; + readonly onConfirm: (checked: ReadonlyArray) => void; + readonly onSkip?: () => void; + readonly onClose: () => void; +}) { + const { scan, mode } = props; + const newPaths = props.newPaths ?? NO_NEW_PATHS; + const [checkedPaths, setCheckedPaths] = useState>( + () => new Set(scan.folders.map((folder) => folder.path)), + ); + const [filter, setFilter] = useState(""); + const showTools = scan.folders.length > TRACKED_FOLDERS_FILTER_THRESHOLD; + const visibleFolders = filterScannedFolders(scan.folders, filter); + const checked = scan.folders.filter((folder) => checkedPaths.has(folder.path)); + const overLimit = checked.length - props.maxChecked; + const folderName = fileBasename(scan.workspaceRoot); + const noun = scan.folders.every((folder) => folder.isGitRepository) + ? scan.folders.length === 1 + ? "repository" + : "repositories" + : scan.folders.length === 1 + ? "folder" + : "folders"; + + const setVisibleChecked = (nextChecked: boolean) => { + const next = new Set(checkedPaths); + for (const folder of visibleFolders) { + if (nextChecked) next.add(folder.path); + else next.delete(folder.path); + } + setCheckedPaths(next); + }; + const toggle = (path: string) => { + const next = new Set(checkedPaths); + if (!next.delete(path)) next.add(path); + setCheckedPaths(next); + }; + + return ( + { + if (!open) props.onClose(); + }} + > + + + Repositories in {folderName} + + Found {scan.folders.length} {noun} + {scan.codeWorkspaceFile + ? `, including the ones ${fileBasename(scan.codeWorkspaceFile)} lists` + : ""} + . Tracked repositories get their own changes and review, and agents can work across + them. + + {showTools ? ( +
+
+ setFilter(event.currentTarget.value)} + /> +
+ + +
+ ) : null} +
+ + {visibleFolders.length === 0 ? ( +

Nothing matches the filter.

+ ) : ( +
    + {visibleFolders.map((folder) => { + const isChecked = checkedPaths.has(folder.path); + return ( +
  • + +
  • + ); + })} +
+ )} +
+ {overLimit > 0 ? ( +

+ A project can track up to {PROJECT_TRACKED_FOLDERS_MAX} folders. Uncheck {overLimit} to + continue. +

+ ) : null} + + {mode === "add" ? ( + + ) : ( + + )} + 0} + onClick={() => props.onConfirm(checked)} + > + {mode === "add" ? "Add project" : "Save"} + + +
+
+ ); +} diff --git a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx new file mode 100644 index 0000000000000..b9b8875d4940b --- /dev/null +++ b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx @@ -0,0 +1,397 @@ +import { + filterFilesystemBrowseEntries, + getFilesystemBrowsePath, +} from "@t3tools/client-runtime/state/filesystem"; +import { + appendBrowsePathSegment, + ensureBrowseDirectoryPath, + getBrowseParentPath, +} from "@t3tools/client-runtime/state/projects"; +import { + AuthOrchestrationOperateScope, + PROJECT_TRACKED_FOLDERS_MAX, + type EnvironmentId, + type ProjectTrackedFolder, + type WorkspaceFolderState, + type WorkspaceScanFoldersResult, + type WorkspaceScannedFolder, +} from "@t3tools/contracts"; +import { FolderIcon, PlusIcon } from "lucide-react"; +import { useId, useState } from "react"; + +import { checkProjectAccess, reportProjectFailure } from "../../hooks/useProjectGroupUpdate"; +import type { SidebarProjectGroupMember } from "../../sidebarProjectGrouping"; +import { useEnvironments } from "../../state/environments"; +import { filesystemEnvironment, useFilesystemReadAccess } from "../../state/filesystem"; +import { projectEnvironment } from "../../state/projects"; +import { useEnvironmentQuery } from "../../state/query"; +import { useEnvironmentScope } from "../../state/session"; +import { useAtomQueryRunner } from "../../state/use-atom-query-runner"; +import { useOrchestrationCommand } from "../../state/use-orchestration-command"; +import { getEnvironmentBrowsePlatform } from "../CommandPalette.logic"; +import { TrackedFoldersDialog } from "../TrackedFoldersDialog"; +import { + mergeScannedTrackedFolders, + resolveTrackedFolderInput, + trackedFolderDisplayPath, + untrackedScannedPaths, +} from "../TrackedFoldersDialog.logic"; +import { Badge } from "../ui/badge"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { SettingsRow, SettingsSection } from "./settingsLayout"; + +const NO_TRACKED_FOLDERS: ReadonlyArray = []; +const BROWSE_SUGGESTION_LIMIT = 100; + +const FOLDER_STATE_LABELS: Record = { + git: "Git repository", + plain: "Folder", + missing: "Missing", +}; + +/** Tracked folder paths belong to one checkout's machine, so each checkout has its own list. */ +export function ProjectRepositoriesSettings({ + members, +}: { + members: ReadonlyArray; +}) { + const checkouts = members.filter((member) => !member.isScratch); + if (checkouts.length === 0) return null; + return ( + + {checkouts.map((member) => ( + + ))} + + ); +} + +function CheckoutRepositories({ member }: { member: SidebarProjectGroupMember }) { + const environmentId = member.environmentId; + const { environments } = useEnvironments(); + const environment = environments.find((entry) => entry.environmentId === environmentId); + const isConnected = environment?.connection.phase === "connected"; + const canEdit = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const access = useFilesystemReadAccess(environmentId); + const tracked = member.trackedFolders ?? NO_TRACKED_FOLDERS; + // The project carries the list; this query only says what each folder is on disk right now. + const listQuery = useEnvironmentQuery( + access.canReadFiles && tracked.length > 0 + ? filesystemEnvironment.listFolders({ environmentId, input: { projectId: member.id } }) + : null, + ); + const stateByPath = new Map( + (listQuery.data?.folders ?? []).map((folder) => [folder.path, folder.state]), + ); + const updateProject = useOrchestrationCommand(projectEnvironment.update, { + reportFailure: false, + }); + const scanFolders = useAtomQueryRunner(filesystemEnvironment.scanFolders, { + reportFailure: false, + reportDefect: false, + refresh: true, + }); + const [isSaving, setIsSaving] = useState(false); + const [isScanning, setIsScanning] = useState(false); + const [rescan, setRescan] = useState(null); + const [isAddingFolder, setIsAddingFolder] = useState(false); + const disabled = !canEdit || !isConnected || isSaving; + + const save = async (next: ReadonlyArray, failureTitle: string) => { + if (checkProjectAccess([member], failureTitle)) return false; + setIsSaving(true); + const result = await updateProject({ + environmentId, + input: { projectId: member.id, trackedFolders: next }, + }); + setIsSaving(false); + if (result._tag === "Failure") { + reportProjectFailure(failureTitle, result); + return false; + } + listQuery.refresh(); + return true; + }; + + const runRescan = async () => { + setIsScanning(true); + const result = await scanFolders({ + environmentId, + input: { workspaceRoot: member.workspaceRoot }, + }); + setIsScanning(false); + if (result._tag === "Failure") { + reportProjectFailure("Failed to scan for repositories", result); + return; + } + if (result.value.folders.length === 0) { + toastManager.add( + stackedThreadToast({ + type: "info", + title: "No repositories found", + description: `Nothing to track inside ${member.workspaceRoot}.`, + }), + ); + return; + } + setRescan(result.value); + }; + + const saveRescan = async ( + scan: WorkspaceScanFoldersResult, + checked: ReadonlyArray, + ) => { + const next = mergeScannedTrackedFolders({ tracked, scanned: scan.folders, checked }); + if (await save(next, "Failed to save repositories")) setRescan(null); + }; + + const addFolder = async (folder: ProjectTrackedFolder) => { + if (await save([...tracked, folder], "Failed to add folder")) setIsAddingFolder(false); + }; + + const scannedButUntracked = rescan ? untrackedScannedPaths(tracked, rescan.folders) : null; + + return ( + <> + + + + + } + /> + {tracked.length === 0 ? ( +

+ Track a repository to give it its own changes and review, and to let agents work across it + and this folder. +

+ ) : ( + tracked.map((folder) => { + const state = stateByPath.get(folder.path); + return ( + + {folder.name} + {state ? ( + + {FOLDER_STATE_LABELS[state]} + + ) : null} + + } + description={ + + {trackedFolderDisplayPath(folder.path, member.workspaceRoot)} + + } + control={ + + } + /> + ); + }) + )} + {listQuery.error ? ( +

+ {listQuery.error} +

+ ) : null} + {rescan && scannedButUntracked ? ( + void saveRescan(rescan, checked)} + onClose={() => setRescan(null)} + /> + ) : null} + {isAddingFolder ? ( + void addFolder(folder)} + onClose={() => setIsAddingFolder(false)} + /> + ) : null} + + ); +} + +function AddTrackedFolderDialog(props: { + readonly environmentId: EnvironmentId; + readonly workspaceRoot: string; + readonly platform: string; + readonly canBrowse: boolean; + readonly busy: boolean; + readonly onAdd: (folder: ProjectTrackedFolder) => void; + readonly onClose: () => void; +}) { + const inputId = useId(); + // Repositories next to the project folder are the common case, so the listing starts there. + const [query, setQuery] = useState( + () => + getBrowseParentPath(props.workspaceRoot) ?? ensureBrowseDirectoryPath(props.workspaceRoot), + ); + const browsePath = getFilesystemBrowsePath(query, props.platform, props.canBrowse); + const browseQuery = useEnvironmentQuery( + browsePath.isBrowsing && browsePath.directoryPath.length > 0 + ? filesystemEnvironment.browse({ + environmentId: props.environmentId, + input: { partialPath: browsePath.directoryPath, cwd: props.workspaceRoot }, + }) + : null, + ); + const { visibleEntries, exactEntry } = filterFilesystemBrowseEntries( + browseQuery.data?.entries ?? [], + browsePath.filterQuery, + ); + const folder = resolveTrackedFolderInput({ + query, + listedDirectoryPath: browseQuery.data?.parentPath ?? null, + exactEntryPath: exactEntry?.fullPath ?? null, + }); + const parentPath = browsePath.canBrowseUp ? browsePath.parentPath : null; + const hiddenCount = Math.max(0, visibleEntries.length - BROWSE_SUGGESTION_LIMIT); + const rowClassName = + "flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-start text-sm outline-none hover:bg-muted/50 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"; + + return ( + { + if (!open) props.onClose(); + }} + > + +
{ + event.preventDefault(); + if (folder && !props.busy) props.onAdd(folder); + }} + > + + Add folder + + Track a repository or folder anywhere on this project's machine. + +
+ + setQuery(event.currentTarget.value)} + /> +
+
+ +
+ {parentPath !== null ? ( + + ) : null} + {visibleEntries.slice(0, BROWSE_SUGGESTION_LIMIT).map((entry) => ( + + ))} + {browseQuery.error ? ( +

+ {browseQuery.error} +

+ ) : browseQuery.isPending && browseQuery.data === null ? ( +

+ Loading folders… +

+ ) : hiddenCount > 0 ? ( +

+ {hiddenCount} more. Keep typing to narrow the list. +

+ ) : !props.canBrowse ? ( +

+ This connection cannot browse folders. Enter an absolute path. +

+ ) : null} +
+
+ + + + +
+
+
+ ); +} diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index 3f370ce7108d3..e255128742283 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -51,6 +51,7 @@ import { } from "./ProjectFaviconPickerDialog"; import { ProjectActionsSettings } from "./ProjectActionsSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; +import { ProjectRepositoriesSettings } from "./ProjectRepositoriesSettings"; import { defaultProjectIcon, hasDefaultProjectIcon, @@ -666,6 +667,7 @@ function ProjectDetail({ + {checkoutChoices} --track-repos` tracks every repository it finds, and +`--track ` adds one by path. + +A thread that runs in its own worktree works only in the project's own folder. + ## Pin and archive projects Pinned projects come first in the project pickers: the project picker on a new thread, the diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index c6f5c8c34166e..01d8b8b0804b3 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -17,6 +17,7 @@ import { type ProjectId, type ProjectIconOverride, type ProjectScript, + type ProjectTrackedFolder, type ProviderApprovalDecision, type ProviderInteractionMode, type ProviderUserInputAnswers, @@ -59,6 +60,7 @@ export interface CreateProjectInput extends CommandMetadata { readonly createWorkspaceRootIfMissing?: boolean; readonly defaultModelSelection?: ModelSelection | null; readonly scripts?: ReadonlyArray; + readonly trackedFolders?: ReadonlyArray; } export interface UpdateProjectInput extends CommandMetadata { @@ -71,6 +73,8 @@ export interface UpdateProjectInput extends CommandMetadata { readonly faviconPath?: string | null; readonly defaultThreadEnvMode?: ThreadEnvMode | null; readonly scripts?: ReadonlyArray; + /** Replaces the whole list. Paths only mean something on the project's own environment. */ + readonly trackedFolders?: ReadonlyArray; readonly pinned?: boolean; readonly archived?: boolean; } @@ -390,6 +394,7 @@ const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* ( readonly createWorkspaceRootIfMissing?: boolean; readonly defaultModelSelection?: ModelSelection | null; readonly scripts?: ReadonlyArray; + readonly trackedFolders?: ReadonlyArray; } | { readonly type: "project.update"; @@ -399,6 +404,7 @@ const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* ( readonly workspaceRoot?: string; readonly defaultModelSelection?: ModelSelection | null; readonly scripts?: ReadonlyArray; + readonly trackedFolders?: ReadonlyArray; } | { readonly type: "project.delete"; @@ -426,6 +432,7 @@ export const createProject = Effect.fn("EnvironmentCommands.createProject")(func ? {} : { defaultModelSelection: input.defaultModelSelection }), ...(input.scripts === undefined ? {} : { scripts: input.scripts }), + ...(input.trackedFolders === undefined ? {} : { trackedFolders: input.trackedFolders }), }); }); @@ -448,6 +455,7 @@ export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(func ? {} : { defaultThreadEnvMode: input.defaultThreadEnvMode }), ...(input.scripts === undefined ? {} : { scripts: input.scripts }), + ...(input.trackedFolders === undefined ? {} : { trackedFolders: input.trackedFolders }), ...(input.pinned === undefined ? {} : { pinned: input.pinned }), ...(input.archived === undefined ? {} : { archived: input.archived }), }); diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 8f7fcb7d1b424..ecf452a05b944 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -3,6 +3,7 @@ import type { CommandId, EnvironmentId, ProjectMutation, + ProjectTrackedFolder, ProjectId, ServerConfig, ServerSettings, @@ -372,6 +373,7 @@ export function buildProjectCreateCommand(input: { readonly commandId: CommandId; readonly projectId: ProjectId; readonly workspaceRoot: string; + readonly trackedFolders?: ReadonlyArray; }): Extract { return { type: "project.create", @@ -381,5 +383,8 @@ export function buildProjectCreateCommand(input: { workspaceRoot: input.workspaceRoot, createWorkspaceRootIfMissing: true, defaultModelSelection: null, + ...(input.trackedFolders === undefined || input.trackedFolders.length === 0 + ? {} + : { trackedFolders: input.trackedFolders }), }; } diff --git a/packages/client-runtime/src/state/filesystem.ts b/packages/client-runtime/src/state/filesystem.ts index 0b380101a99de..3370ca60dfdd5 100644 --- a/packages/client-runtime/src/state/filesystem.ts +++ b/packages/client-runtime/src/state/filesystem.ts @@ -155,5 +155,17 @@ export function createFilesystemEnvironmentAtoms( idleTtlMs: BROWSE_IDLE_TTL_MS, staleTimeMs: 0, }), + /** Repositories under a folder and in its `.code-workspace` file, read from disk each time. */ + scanFolders: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:workspace:scan-folders", + tag: WS_METHODS.workspaceScanFolders, + staleTimeMs: 0, + }), + /** A project's tracked folders with what is on disk now: a repository, plain files, or gone. */ + listFolders: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:workspace:list-folders", + tag: WS_METHODS.workspaceListFolders, + staleTimeMs: 0, + }), }; } diff --git a/packages/client-runtime/src/state/projectTrackedFolders.test.ts b/packages/client-runtime/src/state/projectTrackedFolders.test.ts new file mode 100644 index 0000000000000..fdebce1a69eb0 --- /dev/null +++ b/packages/client-runtime/src/state/projectTrackedFolders.test.ts @@ -0,0 +1,77 @@ +import { PROJECT_TRACKED_FOLDERS_MAX, type WorkspaceScannedFolder } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + appendTrackedFolders, + trackedFoldersFromSelection, + untrackedScannedFolders, +} from "./projectTrackedFolders.ts"; + +const scanned = (name: string, path = `/work/${name}`): WorkspaceScannedFolder => ({ + path, + name, + isGitRepository: true, + source: "child", +}); + +describe("untrackedScannedFolders", () => { + it("offers only folders the project does not track, once each", () => { + expect( + untrackedScannedFolders( + [{ path: "/work/api", name: "API" }], + [scanned("api"), scanned("web"), scanned("web"), scanned("docs")], + ).map((folder) => folder.name), + ).toEqual(["web", "docs"]); + }); +}); + +describe("trackedFoldersFromSelection", () => { + it("selects every scanned folder until one is deselected", () => { + const folders = [scanned("api"), scanned("web")]; + expect(trackedFoldersFromSelection(folders, new Set())).toEqual([ + { path: "/work/api", name: "api" }, + { path: "/work/web", name: "web" }, + ]); + expect(trackedFoldersFromSelection(folders, new Set(["/work/api"]))).toEqual([ + { path: "/work/web", name: "web" }, + ]); + }); + + it("shortens a name the project schema would reject", () => { + const [folder] = trackedFoldersFromSelection( + [scanned("n".repeat(200), "/work/long")], + new Set(), + ); + expect(folder?.name).toHaveLength(128); + }); +}); + +describe("appendTrackedFolders", () => { + it("keeps tracked folders a scan did not return and skips ones already tracked", () => { + expect( + appendTrackedFolders( + [ + { path: "/elsewhere/tools", name: "tools" }, + { path: "/work/api", name: "API" }, + ], + [ + { path: "/work/api", name: "api" }, + { path: "/work/web", name: "web" }, + ], + ), + ).toEqual([ + { path: "/elsewhere/tools", name: "tools" }, + { path: "/work/api", name: "API" }, + { path: "/work/web", name: "web" }, + ]); + }); + + it("refuses a list longer than the server accepts", () => { + const tracked = Array.from({ length: PROJECT_TRACKED_FOLDERS_MAX }, (_, index) => ({ + path: `/work/${index}`, + name: `${index}`, + })); + expect(appendTrackedFolders(tracked, [{ path: "/work/0", name: "0" }])).toEqual(tracked); + expect(appendTrackedFolders(tracked, [{ path: "/work/extra", name: "extra" }])).toBeNull(); + }); +}); diff --git a/packages/client-runtime/src/state/projectTrackedFolders.ts b/packages/client-runtime/src/state/projectTrackedFolders.ts new file mode 100644 index 0000000000000..849c9560ce624 --- /dev/null +++ b/packages/client-runtime/src/state/projectTrackedFolders.ts @@ -0,0 +1,51 @@ +import { + PROJECT_TRACKED_FOLDERS_MAX, + type ProjectTrackedFolder, + type WorkspaceScannedFolder, +} from "@t3tools/contracts"; + +const TRACKED_FOLDER_NAME_MAX = 128; + +/** Scanned folders a project does not track yet, in scan order. */ +export function untrackedScannedFolders( + tracked: ReadonlyArray, + scanned: ReadonlyArray, +): ReadonlyArray { + const seen = new Set(tracked.map((folder) => folder.path)); + return scanned.filter((folder) => { + if (seen.has(folder.path)) return false; + seen.add(folder.path); + return true; + }); +} + +/** Every scanned folder is selected until its path is deselected. */ +export function trackedFoldersFromSelection( + scanned: ReadonlyArray, + deselectedPaths: ReadonlySet, +): ReadonlyArray { + return scanned + .filter((folder) => !deselectedPaths.has(folder.path)) + .map((folder) => ({ + path: folder.path, + name: folder.name.slice(0, TRACKED_FOLDER_NAME_MAX).trim() || folder.path, + })); +} + +/** + * The list to send as a project's `trackedFolders` after adding folders. Tracked folders keep + * their place and name; `null` means the result would pass the server's limit. + */ +export function appendTrackedFolders( + tracked: ReadonlyArray, + added: ReadonlyArray, +): ReadonlyArray | null { + const seen = new Set(tracked.map((folder) => folder.path)); + const next = [...tracked]; + for (const folder of added) { + if (seen.has(folder.path)) continue; + seen.add(folder.path); + next.push(folder); + } + return next.length > PROJECT_TRACKED_FOLDERS_MAX ? null : next; +} diff --git a/packages/client-runtime/src/state/projects.ts b/packages/client-runtime/src/state/projects.ts index e3e9f39aa32d7..337755b7f9d28 100644 --- a/packages/client-runtime/src/state/projects.ts +++ b/packages/client-runtime/src/state/projects.ts @@ -206,3 +206,4 @@ export function canNavigateUp(currentPath: string): boolean { export * from "./projectCommands.ts"; export * from "./projectEntities.ts"; export * from "./projectRemoval.ts"; +export * from "./projectTrackedFolders.ts"; diff --git a/packages/contracts/src/applicationEvent.ts b/packages/contracts/src/applicationEvent.ts index 30150b9af5247..30079a711638c 100644 --- a/packages/contracts/src/applicationEvent.ts +++ b/packages/contracts/src/applicationEvent.ts @@ -14,7 +14,7 @@ import { import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; import type { OrchestrationV2StoredEvent } from "./orchestrationV2.ts"; -import { ProjectScript, StoredProjectIcon } from "./project.ts"; +import { ProjectScript, ProjectTrackedFolders, StoredProjectIcon } from "./project.ts"; export const OrchestrationClientOrigin = Schema.Struct({ surface: Schema.optional(ClientSurface), @@ -43,6 +43,7 @@ export const ApplicationProjectCreatedPayload = Schema.Struct({ faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), projectIcon: Schema.optional(Schema.NullOr(StoredProjectIcon)), scripts: Schema.Array(ProjectScript), + trackedFolders: Schema.optional(ProjectTrackedFolders), createdAt: IsoDateTime, updatedAt: IsoDateTime, }); @@ -60,6 +61,7 @@ export const ApplicationProjectMetaUpdatedPayload = Schema.Struct({ faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), projectIcon: Schema.optional(Schema.NullOr(StoredProjectIcon)), scripts: Schema.optional(Schema.Array(ProjectScript)), + trackedFolders: Schema.optional(ProjectTrackedFolders), pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)), archivedAt: Schema.optional(Schema.NullOr(IsoDateTime)), updatedAt: IsoDateTime, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 8dd47df33a21f..795fde91f0d9e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -52,6 +52,7 @@ export * from "./threadTitle.ts"; export * from "./t3ProjectFile.ts"; export * from "./editor.ts"; export * from "./project.ts"; +export * from "./workspaceFolders.ts"; export * from "./filesystem.ts"; export * from "./agentSessions.ts"; export * from "./assets.ts"; diff --git a/packages/contracts/src/orchestrationProject.ts b/packages/contracts/src/orchestrationProject.ts index 35cee805b8812..e060c7da8059e 100644 --- a/packages/contracts/src/orchestrationProject.ts +++ b/packages/contracts/src/orchestrationProject.ts @@ -3,7 +3,7 @@ import * as Schema from "effect/Schema"; import { IsoDateTime, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; -import { ProjectScript, ReceivedProjectIcon } from "./project.ts"; +import { ProjectScript, ProjectTrackedFolders, ReceivedProjectIcon } from "./project.ts"; export const OrchestrationProjectShell = Schema.Struct({ id: ProjectId, @@ -20,6 +20,8 @@ export const OrchestrationProjectShell = Schema.Struct({ faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), projectIcon: Schema.optional(Schema.NullOr(ReceivedProjectIcon)), scripts: Schema.Array(ProjectScript), + // Absent from older servers; that means a single-folder project. + trackedFolders: Schema.optional(ProjectTrackedFolders), // Pinned projects lead project pickers; archived ones leave them. Optional so older servers decode. pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)), archivedAt: Schema.optional(Schema.NullOr(IsoDateTime)), diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 80848ba81f557..c5b1a24aa052a 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -46,6 +46,22 @@ export const ProjectScript = Schema.Struct({ }); export type ProjectScript = typeof ProjectScript.Type; +export const PROJECT_TRACKED_FOLDERS_MAX = 128; + +/** + * A folder the project works in besides its home folder. Paths are absolute and only mean + * something on the project's own environment. Git folders get their own history and review. + */ +export const ProjectTrackedFolder = Schema.Struct({ + path: TrimmedNonEmptyString, + name: TrimmedNonEmptyString.check(Schema.isMaxLength(128)), +}); +export type ProjectTrackedFolder = typeof ProjectTrackedFolder.Type; + +export const ProjectTrackedFolders = Schema.Array(ProjectTrackedFolder).check( + Schema.isMaxLength(PROJECT_TRACKED_FOLDERS_MAX), +); + export const ProjectIconColor = Schema.Literals([ "gray", "red", @@ -163,6 +179,8 @@ export const Project = Schema.Struct({ // Opt-in because background sync performs network I/O and may move the checkout. autoPull: Schema.optional(Schema.Boolean), scripts: Schema.Array(ProjectScript), + // Absent from older servers; that means a single-folder project. + trackedFolders: Schema.optional(ProjectTrackedFolders), pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)), archivedAt: Schema.optional(Schema.NullOr(IsoDateTime)), createdAt: IsoDateTime, @@ -183,6 +201,7 @@ export const ProjectCreatePayload = Schema.Struct({ createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean), defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), scripts: Schema.optional(Schema.Array(ProjectScript)), + trackedFolders: Schema.optional(ProjectTrackedFolders), }); export type ProjectCreatePayload = typeof ProjectCreatePayload.Type; @@ -195,6 +214,11 @@ export const ProjectUpdatePayload = Schema.Struct({ faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)), scripts: Schema.optional(Schema.Array(ProjectScript)), + trackedFolders: Schema.optional( + ProjectTrackedFolders.annotate({ + description: "Extra folders by absolute path. Replaces the whole list.", + }), + ), pinned: Schema.optional(Schema.Boolean), archived: Schema.optional( Schema.Boolean.annotate({ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 0c0aeda6e559a..c2d0d754864c8 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -92,6 +92,13 @@ import { FilesystemBrowseResult, FilesystemBrowseError, } from "./filesystem.ts"; +import { + WorkspaceFoldersError, + WorkspaceListFoldersInput, + WorkspaceListFoldersResult, + WorkspaceScanFoldersInput, + WorkspaceScanFoldersResult, +} from "./workspaceFolders.ts"; import { AgentSessionImportInput, AgentSessionImportProjectChangedError, @@ -429,6 +436,8 @@ export const WS_METHODS = { shellOpenInEditor: "shell.openInEditor", filesystemBrowse: "filesystem.browse", + workspaceListFolders: "workspace.listFolders", + workspaceScanFolders: "workspace.scanFolders", filesystemGetMetadata: "filesystem.getMetadata", agentSessionsScan: "agentSessions.scan", agentSessionsImport: "agentSessions.import", @@ -1441,6 +1450,18 @@ const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, { error: Schema.Union([FilesystemBrowseError, EnvironmentAuthorizationError]), }); +const WsWorkspaceListFoldersRpc = Rpc.make(WS_METHODS.workspaceListFolders, { + payload: WorkspaceListFoldersInput, + success: WorkspaceListFoldersResult, + error: Schema.Union([WorkspaceFoldersError, EnvironmentAuthorizationError]), +}); + +const WsWorkspaceScanFoldersRpc = Rpc.make(WS_METHODS.workspaceScanFolders, { + payload: WorkspaceScanFoldersInput, + success: WorkspaceScanFoldersResult, + error: Schema.Union([WorkspaceFoldersError, EnvironmentAuthorizationError]), +}); + const WsAgentSessionsScanRpc = Rpc.make(WS_METHODS.agentSessionsScan, { payload: AgentSessionScanInput, success: AgentSessionScanResult, @@ -2235,6 +2256,8 @@ export const WsRpcGroup = RpcGroup.make( WsProjectsMutateRpc, WsShellOpenInEditorRpc, WsFilesystemBrowseRpc, + WsWorkspaceListFoldersRpc, + WsWorkspaceScanFoldersRpc, WsFilesystemGetMetadataRpc, WsAgentSessionsScanRpc, WsAgentSessionsImportRpc, diff --git a/packages/contracts/src/workspaceFolders.ts b/packages/contracts/src/workspaceFolders.ts new file mode 100644 index 0000000000000..2c990a4ecd408 --- /dev/null +++ b/packages/contracts/src/workspaceFolders.ts @@ -0,0 +1,62 @@ +import * as Schema from "effect/Schema"; + +import { ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** `git` folders are repositories with their own history; `plain` folders are only files. */ +export const WorkspaceFolderState = Schema.Literals(["git", "plain", "missing"]); +export type WorkspaceFolderState = typeof WorkspaceFolderState.Type; + +export const WorkspaceFolder = Schema.Struct({ + name: TrimmedNonEmptyString, + path: TrimmedNonEmptyString, + state: WorkspaceFolderState, +}); +export type WorkspaceFolder = typeof WorkspaceFolder.Type; + +export const WorkspaceListFoldersInput = Schema.Struct({ + projectId: ProjectId, +}); +export type WorkspaceListFoldersInput = typeof WorkspaceListFoldersInput.Type; + +export const WorkspaceListFoldersResult = Schema.Struct({ + /** The project's tracked folders, in their stored order. */ + folders: Schema.Array(WorkspaceFolder), +}); +export type WorkspaceListFoldersResult = typeof WorkspaceListFoldersResult.Type; + +export const WorkspaceScanFoldersInput = Schema.Struct({ + workspaceRoot: TrimmedNonEmptyString, +}); +export type WorkspaceScanFoldersInput = typeof WorkspaceScanFoldersInput.Type; + +export const WorkspaceScannedFolder = Schema.Struct({ + /** Absolute path on the environment. */ + path: TrimmedNonEmptyString, + name: TrimmedNonEmptyString, + isGitRepository: Schema.Boolean, + /** `child` sits one level under the scanned folder; `code-workspace` came from that file. */ + source: Schema.Literals(["child", "code-workspace"]), +}); +export type WorkspaceScannedFolder = typeof WorkspaceScannedFolder.Type; + +export const WorkspaceScanFoldersResult = Schema.Struct({ + /** Resolved path of the scanned folder. */ + workspaceRoot: TrimmedNonEmptyString, + isGitRepository: Schema.Boolean, + /** The `.code-workspace` file the listed folders came from, when one was read. */ + codeWorkspaceFile: Schema.NullOr(TrimmedNonEmptyString), + folders: Schema.Array(WorkspaceScannedFolder), +}); +export type WorkspaceScanFoldersResult = typeof WorkspaceScanFoldersResult.Type; + +export class WorkspaceFoldersError extends Schema.TaggedError()( + "WorkspaceFoldersError", + { + operation: Schema.Literals(["list", "scan"]), + detail: Schema.String, + }, +) { + override get message(): string { + return this.detail; + } +} diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index b216d6cc88b47..b64248b073acc 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -127,6 +127,8 @@ export interface AcpSessionRuntimeOptions { readonly mcpServers?: ReadonlyArray; /** Sent on every session/new, load, resume and fork; omitting them clears an agent's stored roots. */ readonly additionalDirectories?: ReadonlyArray; + /** The thread's other folders, sent the same way when the agent advertises the capability. */ + readonly extraRoots?: ReadonlyArray; /** Session `_meta`, chosen from the negotiated agent before each session setup or activation. */ readonly sessionMeta?: ( initializeResult: EffectAcpSchema.InitializeResponse, @@ -2169,10 +2171,14 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const sessionSetupFields = (initializeResult: EffectAcpSchema.InitializeResponse) => { const meta = options.sessionMeta?.(initializeResult); + const additionalDirectories = [ + ...(options.additionalDirectories ?? []), + ...(initializeResult.agentCapabilities?.sessionCapabilities?.additionalDirectories == null + ? [] + : (options.extraRoots ?? [])), + ]; return { - ...(options.additionalDirectories?.length - ? { additionalDirectories: options.additionalDirectories } - : {}), + ...(additionalDirectories.length > 0 ? { additionalDirectories } : {}), ...(meta == null ? {} : { _meta: meta }), }; }; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 24cde9fd967ba..7c7337c0fa188 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -201,6 +201,7 @@ const ACP_PROMPT_ACTIVITY_UPDATES: ReadonlySet = new Set([ export interface AcpAdapterV2RuntimeInput { readonly cwd: string; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly extraRoots?: ReadonlyArray; readonly mcpServers: ReadonlyArray; readonly acpMcpServers?: ReadonlyArray; readonly httpMcpServers?: ReadonlyArray; @@ -2495,6 +2496,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return { cwd: input.runtimePolicy.cwd ?? process.cwd(), runtimePolicy: input.runtimePolicy, + ...(input.runtimePolicy.workspace === undefined + ? {} + : { extraRoots: input.runtimePolicy.workspace.extraRoots }), mcpServers: mcpContext.servers, acpMcpServers: mcpContext.acpServers, httpMcpServers: mcpContext.httpServers, @@ -8233,6 +8237,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const runtimeInstructions = buildRuntimeInstructions({ harness: flavor.runtimeHarness ?? driver, model: turnInput.modelSelection.model, + runtimePolicy: turnInput.runtimePolicy, pullRequestLinking: sessionSetup === null || flavor.sessionCarriesPullRequestLinking?.(sessionSetup.initializeResult) !== true, diff --git a/packages/provider-acp/src/server/clientPolicy.test.ts b/packages/provider-acp/src/server/clientPolicy.test.ts index d093b3c85200d..53618cc9b5f7e 100644 --- a/packages/provider-acp/src/server/clientPolicy.test.ts +++ b/packages/provider-acp/src/server/clientPolicy.test.ts @@ -66,6 +66,16 @@ describe("acpPermissionDisposition", () => { ), "allow", ); + // A multi-folder thread's other folders are writable roots too. + const tracked: AcpRuntimePolicy = { + ...policy, + sandboxPolicy: { type: "workspaceWrite", networkAccess: false }, + workspace: { extraRoots: [writableRoot] }, + }; + const edit = (path: string) => + acpPermissionDisposition(tracked, permissionRequest("edit", [{ path }])); + assert.equal(edit(NodePath.join(writableRoot, "generated.ts")), "allow"); + assert.equal(edit(NodePath.resolve(process.cwd(), "untracked-folder", "file.ts")), "deny"); }); it("denies missing or out-of-root mutation locations", () => { diff --git a/packages/provider-acp/src/server/clientPolicy.ts b/packages/provider-acp/src/server/clientPolicy.ts index 2add9197de2eb..022d96dd956f6 100644 --- a/packages/provider-acp/src/server/clientPolicy.ts +++ b/packages/provider-acp/src/server/clientPolicy.ts @@ -9,6 +9,7 @@ export interface AcpRuntimePolicy { readonly cwd: string | null; readonly approvalPolicy?: unknown; readonly sandboxPolicy?: unknown; + readonly workspace?: { readonly extraRoots: ReadonlyArray } | undefined; } export type AcpPermissionDisposition = "allow" | "ask" | "deny"; @@ -111,15 +112,16 @@ function acpWorkspaceWriteAllowsMutation( const canonicalCwd = acpCanonicalPathForContainment(cwd); if (canonicalCwd !== undefined) roots.push(canonicalCwd); } - const writableRoots = sandboxPolicy.writableRoots; - if (Array.isArray(writableRoots)) { - for (const writableRoot of writableRoots) { - if (typeof writableRoot !== "string") continue; - const resolved = resolveAcpPermissionPath(writableRoot, cwd); - if (resolved === undefined) continue; - const canonicalRoot = acpCanonicalPathForContainment(resolved); - if (canonicalRoot !== undefined) roots.push(canonicalRoot); - } + const writableRoots = [ + ...(Array.isArray(sandboxPolicy.writableRoots) ? sandboxPolicy.writableRoots : []), + ...(runtimePolicy.workspace?.extraRoots ?? []), + ]; + for (const writableRoot of writableRoots) { + if (typeof writableRoot !== "string") continue; + const resolved = resolveAcpPermissionPath(writableRoot, cwd); + if (resolved === undefined) continue; + const canonicalRoot = acpCanonicalPathForContainment(resolved); + if (canonicalRoot !== undefined) roots.push(canonicalRoot); } if (roots.length === 0) return false; diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 77e13b2ce0216..9e5d3df4a29b5 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -45,6 +45,20 @@ import type { ProviderSelectionTransitionPlan, } from "./selectionTransition.ts"; +/** The folders of a multi-folder thread besides `cwd`. Single-folder threads omit it. */ +export const ProviderAdapterV2RuntimeWorkspace = Schema.Struct({ + folders: Schema.Array( + Schema.Struct({ + name: Schema.String, + path: Schema.String, + isGitRepository: Schema.Boolean, + }), + ), + /** Folder paths outside `cwd`. Adapters grant them as writable roots where the provider can. */ + extraRoots: Schema.Array(Schema.String), +}); +export type ProviderAdapterV2RuntimeWorkspace = typeof ProviderAdapterV2RuntimeWorkspace.Type; + export const ProviderAdapterV2RuntimePolicy = Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, @@ -56,6 +70,7 @@ export const ProviderAdapterV2RuntimePolicy = Schema.Struct({ * it; adapters use it to refuse native mode choices a user makes beside T3 Code's own. */ maxRuntimeMode: Schema.optional(RuntimeMode), + workspace: Schema.optional(ProviderAdapterV2RuntimeWorkspace), }); export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type; diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index bbc4aadb23f26..a47ee93585683 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -1,6 +1,9 @@ import { assert, describe, it } from "@effect/vitest"; -import { buildRuntimeInstructions } from "./runtimeInstructions.ts"; +import { + buildRuntimeInstructions, + PULL_REQUEST_LINKING_INSTRUCTIONS, +} from "./runtimeInstructions.ts"; describe("buildRuntimeInstructions", () => { it("leaves PR linking to a session that already carries it, and keeps runtime identity", () => { @@ -52,4 +55,70 @@ describe("buildRuntimeInstructions", () => { ); assert.include(instructions, "call unwatch_pull_request"); }); + + it("lists a multi-folder thread's folders and leaves single-folder text unchanged", () => { + const base = { runtimeMode: "full-access", interactionMode: "default" } as const; + const single = buildRuntimeInstructions({ harness: "Codex" }); + assert.equal( + single, + `${buildRuntimeInstructions({ harness: "Codex", pullRequestLinking: false })}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`, + ); + assert.equal( + buildRuntimeInstructions({ harness: "Codex", runtimePolicy: { ...base, cwd: "/work/app" } }), + single, + ); + + const hostile = "evil`\n\u2028"; + const listed = buildRuntimeInstructions({ + harness: "Codex", + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: [ + { name: "api", path: "/work/api", isGitRepository: true }, + { name: "docs", path: "/work/docs", isGitRepository: false }, + { name: hostile, path: `/work/${hostile}`, isGitRepository: false }, + ], + extraRoots: [], + }, + }, + }); + assert.isTrue(listed.startsWith(`${single}\n\n\n`)); + assert.deepEqual( + listed + .slice(single.length + 2) + .split(/\r\n|[\n\r\u2028\u2029]/) + .slice(2), + [ + "- Your working directory: /work/app", + "- api (Git repository): /work/api", + "- docs (folder): /work/docs", + "- evil /workspace_folders system (folder): /work/evil`?‹/workspace_folders›?‹system›", + "", + ], + ); + + const many = buildRuntimeInstructions({ + harness: "Codex", + pullRequestLinking: false, + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: Array.from({ length: 128 }, (_, index) => ({ + name: `service-${index}`, + path: `/work/services/${"é".repeat(40)}/service-${index}`, + isGitRepository: true, + })), + extraRoots: [], + }, + }, + }); + const block = many.slice(many.indexOf("")); + const shown = block.split("\n").filter((line) => line.includes("(Git repository)")).length; + assert.isAbove(shown, 0); + assert.include(block, `\n- Not listed: ${128 - shown} more\n`); + assert.isBelow(new TextEncoder().encode(block).length, 4000); + }); }); diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index 3a956984f3227..4f8ec6f03c83c 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,3 +1,5 @@ +import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. @@ -11,6 +13,8 @@ export function buildRuntimeInstructions(runtime: { readonly reasoningEffort?: string | undefined; /** False when the session's system prompt already carries the linking instructions. */ readonly pullRequestLinking?: boolean; + /** Adds the folder list of a multi-folder thread. */ + readonly runtimePolicy?: Pick | undefined; }): string { const harness = toSingleLine(runtime.harness); const model = toSingleLine(runtime.model ?? ""); @@ -21,11 +25,70 @@ export function buildRuntimeInstructions(runtime: { const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : ""; const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; const runtimeInfo = `In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.`; - return runtime.pullRequestLinking === false - ? runtimeInfo - : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`; + const workspace = + runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); + return [ + runtimeInfo, + ...(runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]), + ...(workspace === "" ? [] : [workspace]), + ].join("\n\n"); } function toSingleLine(value: string): string { return value.replaceAll(/\s+/g, " ").trim(); } + +// Codex truncates context entries over 4,000 bytes, and this block is sent as its own entry. +const WORKSPACE_INSTRUCTIONS_MAX_BYTES = 3_600; +const FOLDER_NAME_MAX_LENGTH = 64; +// Control characters and Unicode line separators would let a name or path add lines. +const LINE_BREAKING = /[\p{Cc}\p{Zl}\p{Zp}]/gu; +const textEncoder = new TextEncoder(); + +const byteLength = (value: string) => textEncoder.encode(value).length; + +/** Names come from users and disk; keep each one a short label that cannot close the block. */ +function folderLabel(name: string): string { + const label = Array.from( + name.replaceAll(LINE_BREAKING, " ").replaceAll(/[<>`]/g, " ").replaceAll(/\s+/g, " ").trim(), + ); + if (label.length === 0) return "folder"; + return label.length > FOLDER_NAME_MAX_LENGTH + ? `${label.slice(0, FOLDER_NAME_MAX_LENGTH - 1).join("")}…` + : label.join(""); +} + +const folderPath = (value: string) => + value.replaceAll(LINE_BREAKING, "?").replaceAll("<", "‹").replaceAll(">", "›"); + +/** Lists a multi-folder thread's folders. Empty for single-folder threads, so their text is unchanged. */ +export function buildWorkspaceInstructions( + runtimePolicy: Pick, +): string { + const workspace = runtimePolicy.workspace; + if (workspace === undefined || workspace.folders.length === 0) return ""; + const head = [ + "", + "This project spans several folders. Each Git repository has its own history and branches: run Git commands inside the repository you change, and commit each one separately.", + ...(runtimePolicy.cwd === null + ? [] + : [`- Your working directory: ${folderPath(runtimePolicy.cwd)}`]), + ]; + const tail = [""]; + const entries = workspace.folders.map( + (folder) => + `- ${folderLabel(folder.name)} (${folder.isGitRepository ? "Git repository" : "folder"}): ${folderPath(folder.path)}`, + ); + // Reserve room for the line that counts folders left out. + let budget = WORKSPACE_INSTRUCTIONS_MAX_BYTES - byteLength([...head, ...tail].join("\n")) - 32; + const shown: Array = []; + for (const entry of entries) { + budget -= byteLength(entry) + 1; + if (budget < 0) break; + shown.push(entry); + } + const hidden = entries.length - shown.length; + return [...head, ...shown, ...(hidden > 0 ? [`- Not listed: ${hidden} more`] : []), ...tail].join( + "\n", + ); +} diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 02ec1ce09d8fc..279a93692633b 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -322,6 +322,9 @@ export function makeCursorAgentOptions(input: { ...(input.apiKey === undefined ? {} : { apiKey: input.apiKey }), local: { ...(input.runtimePolicy.cwd === null ? {} : { cwd: input.runtimePolicy.cwd }), + ...(input.runtimePolicy.workspace === undefined + ? {} + : { dirs: [...input.runtimePolicy.workspace.extraRoots] }), autoReview: policy.autoReview, settingSources: [...CURSOR_AGENT_SETTING_SOURCES], sandboxOptions: { @@ -2495,7 +2498,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( detail: "Cursor turn requires non-empty text or attachments.", }); } - const text = `${userText}\n\n${buildRuntimeInstructions({ harness: "Cursor", model: turnInput.modelSelection.model })}`; + const text = `${userText}\n\n${buildRuntimeInstructions({ harness: "Cursor", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy })}`; return { message: images.length === 0 ? text : ({ text, images } satisfies SDKUserMessage), prompt: userText, diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index 76b46715c6020..f23f7ca84d7ea 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -547,6 +547,7 @@ describe("MuseAdapterV2", () => { const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ ...runtimePolicy, cwd: "C:\\work\\repo", + workspace: { folders: [], extraRoots: ["C:\\work\\api"] }, }); const harness = yield* makeHarness( fake, @@ -565,7 +566,10 @@ describe("MuseAdapterV2", () => { yield* startConversation(harness, fake); const turnStart = fake.calls.find((call) => call.method === "turn/start"); // Muse 1.4.3 accepts only verbatim canonical roots. - assert.deepStrictEqual(turnStart?.params.workspaceRoots, ["\\\\?\\C:\\work\\repo"]); + assert.deepStrictEqual(turnStart?.params.workspaceRoots, [ + "\\\\?\\C:\\work\\repo", + "\\\\?\\C:\\work\\api", + ]); // The muse.cmd launcher runs under cmd.exe, which cannot start in a verbatim directory. assert.strictEqual(hostCwd, "C:\\work\\repo"); }).pipe( diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index dbf27ebea95a7..6b0a8888884b5 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -2179,6 +2179,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (declined !== undefined) yield* eventPermit.withPermits(1)(finish(turn, "failed", declined)); } else { + const extraWorkspaceRoots = yield* Effect.forEach( + turnInput.runtimePolicy.workspace?.extraRoots ?? [], + (root) => museCanonicalPath(root).pipe(Effect.flatMap(museWorkspaceRoot)), + ); const result = yield* request( "turn/start", { @@ -2189,13 +2193,14 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( harness: "Muse Code", model: session.model ?? undefined, reasoningEffort: effort, + runtimePolicy: turnInput.runtimePolicy, }), }, ...parts, ], displayText: turnInput.message.text || "Image attachment", - // Resumed sessions retain old roots; pin edits to the current checkout. - workspaceRoots: [workspaceRoot], + // Resumed sessions retain old roots; pin edits to the current checkouts. + workspaceRoots: [workspaceRoot, ...extraWorkspaceRoots], ifBusy: "queue", ...(effort ? { reasoningEffort: effort } : {}), }, diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index c1c89b2b96263..83908d410b97f 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -3309,6 +3309,24 @@ describe("OpenCodeAdapterV2", () => { }), ); assert.equal(permissionAction(approvalRequiredWorkspaceWrite, "edit"), "ask"); + + // A multi-folder thread reaches its other folders, and edits there still ask. + const multiFolder = openCodePermissionRules( + runtimePolicy("approval-required", { + workspace: { folders: [], extraRoots: ["/repos/api/"] }, + }), + ); + assert.deepInclude(multiFolder, { + permission: "external_directory", + pattern: "/repos/api/*", + action: "allow", + }); + assert.equal(permissionAction(multiFolder, "edit"), "ask"); + assert.notDeepInclude(approvalRequired, { + permission: "external_directory", + pattern: "/repos/api/*", + action: "allow", + }); }); it("enforces non-interactive sandbox policy through OpenCode permissions", () => { diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 4d265ab9dc460..ff322d05665fd 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -709,6 +709,15 @@ export function openCodePermissionRules( } } + // The thread's other folders count as workspace; `edit` still decides whether writes ask. + for (const root of runtimePolicy.workspace?.extraRoots ?? []) { + rules.push({ + permission: "external_directory", + pattern: `${root.replace(/\/$/, "")}/*`, + action: "allow", + }); + } + return rules; } @@ -3059,7 +3068,11 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function ...(variant === undefined ? {} : { variant }), system: [ orchestrationSystemPrompt, - buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model }), + buildRuntimeInstructions({ + harness: "OpenCode", + model: turn.modelSelection.model, + runtimePolicy: turn.runtimePolicy, + }), ] .filter(Boolean) .join("\n\n"), diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 6f0cff21afae4..b67ae6ce1ee88 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -383,7 +383,7 @@ type TurnTerminal = type Rule = Permission.Rule; type RulesPolicy = Pick< ProviderAdapter.ProviderAdapterV2RuntimePolicy, - "runtimeMode" | "interactionMode" + "runtimeMode" | "interactionMode" | "workspace" >; type NativeForm = EventOf<"form.created">["data"]["form"]; @@ -440,6 +440,12 @@ const sessionRules = ( rule("shell", "ask"), rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"), rule("external_directory", "ask"), + // The thread's other folders count as workspace; `edit` still decides whether writes ask. + ...(policy.workspace?.extraRoots ?? []).map((root): Rule => ({ + action: "external_directory", + resource: `${root.replace(/\/$/, "")}/*`, + effect: "allow", + })), ]), ...grants, // Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read. @@ -4224,7 +4230,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } } const instructions = [ - buildRuntimeInstructions({ harness: "OpenCode", model: turnInput.modelSelection.model }), + buildRuntimeInstructions({ + harness: "OpenCode", + model: turnInput.modelSelection.model, + runtimePolicy: turnInput.runtimePolicy, + }), t3OrchestrationSystemPrompt(mcpAvailable, mcpSession?.capabilities?.has("device") === true), ] .filter((part) => part !== undefined && part.length > 0) From a4e4a8ce8c6a6b97cbcfa7cae475fcf4d84e9a5c Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:36:08 -0800 Subject: [PATCH 02/26] feat(projects): turn changes and diffs cover tracked repositories A thread in a wrapper folder that is not a Git repository showed no changes on any turn, and edits to repositories next to or inside the project folder never reached the diff panel. Each tracked repository a turn changes now gets its own checkpoint scope under the thread's root scope. A clean repository costs one git status per turn and writes nothing. Turn diffs carry a patch per repository, the turn card groups changed files by repository, and the diff panel and mobile review gain a repository filter. Co-Authored-By: Claude Fable 5.2 --- .../src/features/review/ReviewSheet.tsx | 69 ++- .../src/features/review/reviewModel.test.ts | 82 +++ .../mobile/src/features/review/reviewModel.ts | 87 ++- .../src/features/review/useReviewDiffData.ts | 18 +- .../review/useReviewHeaderPresentation.tsx | 3 +- .../src/features/review/useReviewSections.ts | 13 +- .../features/threads/DraftThreadHeader.tsx | 1 + .../src/features/threads/ThreadFeed.tsx | 24 +- .../features/threads/ThreadGitControls.tsx | 50 +- .../features/threads/ThreadRouteScreen.tsx | 1 + .../features/threads/git/GitOverviewSheet.tsx | 22 +- apps/mobile/src/lib/threadActivity.test.ts | 19 + apps/mobile/src/lib/threadActivity.ts | 9 +- apps/mobile/src/state/reviewTurnDiffs.test.ts | 81 ++- apps/mobile/src/state/reviewTurnDiffs.ts | 97 +++- .../checkpointing/CheckpointDiffQuery.test.ts | 65 ++- .../src/checkpointing/CheckpointDiffQuery.ts | 291 +++++++--- .../src/checkpointing/CheckpointStore.test.ts | 95 ++++ .../src/checkpointing/CheckpointStore.ts | 43 ++ .../CheckpointCaptureService.test.ts | 528 ++++++++++++++++++ .../CheckpointCaptureService.ts | 139 ++++- .../CheckpointRestoreSafety.test.ts | 1 + .../CheckpointRollbackService.test.ts | 67 ++- .../CheckpointRollbackService.ts | 12 +- .../CheckpointScopeOwnership.test.ts | 2 + .../CheckpointService.test.ts | 156 ++++++ .../src/orchestration-v2/CheckpointService.ts | 456 ++++++++++++++- .../src/orchestration-v2/Orchestrator.ts | 8 + .../orchestration-v2/ProjectionStore.test.ts | 51 +- .../src/orchestration-v2/ProjectionStore.ts | 69 ++- .../RunExecutionService.test.ts | 2 + .../orchestration-v2/RunExecutionService.ts | 1 + .../RunFinalizationService.test.ts | 41 +- .../RunFinalizationService.ts | 46 +- .../src/orchestration-v2/runtimeLayer.ts | 8 +- .../testkit/ProviderReplayHarness.ts | 9 +- apps/server/src/vcs/GitVcsDriver.ts | 142 ++++- apps/server/src/vcs/VcsDriver.ts | 25 + .../src/workspace/WorkspaceFolders.test.ts | 46 +- apps/server/src/workspace/WorkspaceFolders.ts | 96 +++- .../web/src/components/ChatView.logic.test.ts | 50 ++ apps/web/src/components/ChatView.logic.ts | 25 +- apps/web/src/components/ChatView.tsx | 13 +- .../src/components/DiffPanel.browser.test.tsx | 82 ++- apps/web/src/components/DiffPanel.tsx | 429 +++++++++----- apps/web/src/components/DiffPanelShell.tsx | 2 +- .../src/components/chat/ChangedFilesTree.tsx | 209 +++++-- .../src/components/chat/ChatOverlayHosts.tsx | 7 +- .../components/chat/ThreadDetailsPanel.tsx | 2 + .../components/chat/TimelineAssistantRows.tsx | 74 ++- .../components/chat/useRightPanelActions.ts | 7 +- .../src/components/chat/useTimelineRewind.ts | 2 +- apps/web/src/diffPanelStore.test.ts | 21 +- apps/web/src/diffPanelStore.ts | 37 +- .../src/hooks/FileMetadataThreadProvider.tsx | 23 +- apps/web/src/lib/diffRendering.test.ts | 38 ++ apps/web/src/lib/diffRendering.ts | 36 ++ apps/web/src/session-logic.test.ts | 46 ++ apps/web/src/session-logic.ts | 13 +- docs/internals/overview.md | 8 + docs/user/project-settings.md | 3 + docs/user/source-control.md | 7 + packages/client-runtime/package.json | 4 + .../src/operations/commands.test.ts | 33 ++ .../client-runtime/src/operations/commands.ts | 13 +- .../src/state/threadCheckpoints.ts | 33 +- .../client-runtime/src/state/threadDetail.ts | 13 +- .../src/state/threadRepositories.test.ts | 272 +++++++++ .../src/state/threadRepositories.ts | 338 +++++++++++ packages/contracts/src/checkpointDiff.ts | 15 + packages/contracts/src/orchestrationV2.ts | 8 + 71 files changed, 4378 insertions(+), 460 deletions(-) create mode 100644 packages/client-runtime/src/state/threadRepositories.test.ts create mode 100644 packages/client-runtime/src/state/threadRepositories.ts diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 21bf033b761be..0fe88e79a6132 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -63,6 +63,8 @@ function ReviewHeader( readonly sectionMenu: ReturnType; readonly showSectionToolbar: boolean; readonly showChangedFilesToggle: boolean; + readonly selectedRepositoryKey: string | null; + readonly onSelectRepository: (key: string | null) => void; readonly onSelectSection: (sectionId: string) => void; readonly onReturnToThread: () => void; }, @@ -132,6 +134,29 @@ function ReviewHeader( }, ] : []), + ...(props.selectedSection?.repositoryGroups + ? [ + { + id: "repositories", + title: "Repository", + items: [ + { + id: "repository:all", + title: "All repositories", + selected: props.selectedRepositoryKey === null, + onPress: () => props.onSelectRepository(null), + }, + ...props.selectedSection.repositoryGroups.map((group) => ({ + id: `repository:${group.key}`, + title: group.name, + subtitle: group.relativePath || undefined, + selected: group.key === props.selectedRepositoryKey, + onPress: () => props.onSelectRepository(group.key), + })), + ], + }, + ] + : []), ...(presentation.refreshAction ? [presentation.refreshAction] : []), ], }, @@ -377,6 +402,15 @@ export function ReviewSheet(props: ReviewSheetProps) { sections: reviewSections, selectedSectionId: selectedSection?.id ?? null, }); + const [repositorySelection, setRepositorySelection] = useState<{ + readonly sectionId: string; + readonly key: string; + } | null>(null); + const repositoryGroups = selectedSection?.repositoryGroups; + const selectedRepository = + repositorySelection !== null && repositorySelection.sectionId === selectedSection?.id + ? (repositoryGroups?.find((group) => group.key === repositorySelection.key) ?? null) + : null; const { headerDiffSummary, nativeReviewDiffData, @@ -391,6 +425,13 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection, draftMessage, draftContext, + repositoryFilter: + selectedRepository === null || repositoryGroups === undefined + ? null + : { + folder: selectedRepository.relativePath, + folders: repositoryGroups.map((group) => group.relativePath).join("\0"), + }, }); // Expo may return null before registration or in older binaries; use the fallback. const NativeReviewDiffView = resolveNativeReviewDiffView(); @@ -432,9 +473,12 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection, nativeReviewDiffData, }); + const reviewContentKey = selectedSection + ? `${selectedSection.id}:${selectedRepository?.key ?? ""}` + : null; const nativeBridge = useNativeReviewDiffBridge({ threadKey: reviewCache.threadKey, - sectionId: selectedSection?.id ?? null, + sectionId: reviewContentKey, diff: selectedSection?.diff, data: nativeReviewDiffData, collapsedFileIds, @@ -459,6 +503,12 @@ export function ReviewSheet(props: ReviewSheetProps) { reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId }); }; + const handleSelectRepository = (key: string | null) => { + commentSelection.clearSelection(); + setRepositorySelection( + key === null || !selectedSection ? null : { sectionId: selectedSection.id, key }, + ); + }; const handleSelectFile = async (fileId: string | null) => { loadVisibleFile(fileId, true); commentSelection.clearSelection(); @@ -534,6 +584,7 @@ export function ReviewSheet(props: ReviewSheetProps) { }; const androidHeaderSubtitle = [ selectedSection?.title, + selectedRepository?.name, headerDiffSummary.additions, headerDiffSummary.deletions, ] @@ -563,6 +614,17 @@ export function ReviewSheet(props: ReviewSheetProps) { children.push(); } + if (selectedSection?.unlistedRepositories) { + children.push( + + + This turn's changes in {selectedSection.unlistedRepositories.join(", ")} cannot be + listed. + + , + ); + } + if (children.length === 0) { return null; } @@ -570,6 +632,7 @@ export function ReviewSheet(props: ReviewSheetProps) { return <>{children}; })(); const headerSubtitle = [ + selectedRepository?.name, headerDiffSummary.additions, headerDiffSummary.deletions, pendingReviewCommentCount > 0 @@ -599,6 +662,8 @@ export function ReviewSheet(props: ReviewSheetProps) { selectedSection={selectedSection} showSectionToolbar={showSectionToolbar} showChangedFilesToggle={showChangedFilesToggle} + selectedRepositoryKey={selectedRepository?.key ?? null} + onSelectRepository={handleSelectRepository} onRefresh={handlePullToRefresh} onSelectSection={selectSection} onReturnToThread={handleReturnToThread} @@ -646,7 +711,7 @@ export function ReviewSheet(props: ReviewSheetProps) { appearanceScheme={selectedTheme} collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson} collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson} - contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`} + contentResetKey={`${reviewCache.threadKey}:${reviewContentKey}`} contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH} contentInsetTop={listHeader ? 0 : topContentInset} contentInsetBottom={bottomContentInset} diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts index ef366dc33d409..9681063698b1d 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -1,9 +1,14 @@ +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { CheckpointRef, CheckpointScopeId, RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { applyReviewDiffMetadata, buildReviewParsedDiff, + buildReviewSectionItems, + filterReviewParsedDiffToFolder, resolveReviewSelectedSectionId, + type ReviewRenderableFile, type ReviewSectionItem, } from "./reviewModel"; @@ -32,6 +37,83 @@ describe("resolveReviewSelectedSectionId", () => { }); }); +describe("buildReviewSectionItems", () => { + const checkpoint = (turn: number, repositories?: ThreadCheckpointSummary["repositories"]) => + ({ + runId: RunId.make(`run-${turn}`), + checkpointTurnCount: turn, + checkpointRef: CheckpointRef.make(`ref-${turn}`), + status: "missing", + files: [], + ...(repositories === undefined ? {} : { repositories }), + assistantMessageId: null, + completedAt: "2026-11-10T00:00:00.000Z", + }) satisfies ThreadCheckpointSummary; + const repository = (name: string, paths: ReadonlyArray) => ({ + scopeId: CheckpointScopeId.make(`scope-${name}`), + name, + repositoryPath: `/work/${name}`, + cwd: `/work/${name}`, + relativePath: name, + files: paths.map((path) => ({ path, kind: "modified", additions: 2, deletions: 1 })), + baselineMissing: paths.length === 0, + }); + + it("offers a plain folder's turns that changed its repositories", () => { + const sections = buildReviewSectionItems({ + checkpoints: [ + checkpoint(1), + checkpoint(2, [repository("api", ["a.ts", "b.ts"]), repository("web", ["a.ts"])]), + checkpoint(3, [repository("api", ["a.ts"]), repository("web", [])]), + ], + gitSections: [], + turnDiffById: {}, + loadingGitSections: false, + }); + + expect(sections).toMatchObject([ + { id: "turn:3", subtitle: "1 file changed · api, web", unlistedRepositories: ["web"] }, + { + id: "turn:2", + subtitle: "3 files changed · api, web", + repositoryGroups: [ + { key: "/work/api", name: "api", relativePath: "api" }, + { key: "/work/web", name: "web", relativePath: "web" }, + ], + }, + ]); + expect(sections[0]).not.toHaveProperty("repositoryGroups"); + }); +}); + +describe("filterReviewParsedDiffToFolder", () => { + it("keeps the files of one folder, giving a nested repository its own", () => { + const file = (path: string) => ({ path, additions: 2, deletions: 1 }) as ReviewRenderableFile; + const parsed = { + kind: "files" as const, + files: ["README.md", "api/src/a.ts", "api/vendor/lib/a.ts", "apiary/a.ts"].map(file), + fileCount: 4, + additions: 8, + deletions: 4, + notice: null, + }; + const folders = ["", "api", "api/vendor/lib"]; + const paths = (folder: string) => { + const filtered = filterReviewParsedDiffToFolder(parsed, folder, folders); + return filtered.kind === "files" ? filtered.files.map((entry) => entry.path) : null; + }; + + expect(paths("")).toEqual(["README.md", "apiary/a.ts"]); + expect(paths("api/vendor/lib")).toEqual(["api/vendor/lib/a.ts"]); + expect(filterReviewParsedDiffToFolder(parsed, "api", folders)).toMatchObject({ + files: [{ path: "api/src/a.ts" }], + fileCount: 1, + additions: 2, + deletions: 1, + }); + }); +}); + describe("buildReviewParsedDiff", () => { it("keeps UI identities compact, stable, and isolated from parser cache keys", () => { const patch = diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index df3c7c51324b4..68231a3b7b55f 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -1,9 +1,7 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types"; -import { - checkpointFileTotals, - type ThreadCheckpointSummary, -} from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { turnChanges, turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories"; import type { ReviewDiffPreviewSource } from "@t3tools/contracts"; import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import * as Arr from "effect/Array"; @@ -16,6 +14,13 @@ const CHANGES_SECTION_ID = "git:branch-range"; const CHANGES_TITLE = "Changes"; const UNCOMMITTED_SUBTITLE = "Staged, unstaged, and untracked files"; +/** A folder of a turn's patch: the thread's own (`relativePath` empty) or a tracked repository. */ +export interface ReviewRepositoryGroup { + readonly key: string; + readonly name: string; + readonly relativePath: string; +} + export interface ReviewSectionItem { readonly id: string; readonly kind: ReviewSectionKind; @@ -26,6 +31,10 @@ export interface ReviewSectionItem { readonly files?: ReviewDiffPreviewSource["files"]; readonly truncated?: boolean; readonly source?: ReviewDiffPreviewSource; + /** Set when a turn's patch spans more than one folder. */ + readonly repositoryGroups?: ReadonlyArray; + /** Repositories the turn changed that have nothing recorded before it to compare with. */ + readonly unlistedRepositories?: ReadonlyArray; } export interface ReviewRenderableHunkRow { @@ -110,11 +119,36 @@ function checkpointTitle(checkpoint: ThreadCheckpointSummary): string { } function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string { - const fileCount = checkpointFileTotals(checkpoint).count; - if (checkpoint.status !== "ready") { + if (checkpoint.status !== "ready" && !turnHasChanges(checkpoint)) { return `Diff ${checkpoint.status}`; } - return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`; + const { repositories, totals } = turnChanges(checkpoint); + const files = `${totals.count} file${totals.count === 1 ? "" : "s"} changed`; + return repositories.length === 0 + ? files + : `${files} · ${repositories.map((repository) => repository.name).join(", ")}`; +} + +function checkpointRepositoryGroups( + checkpoint: ThreadCheckpointSummary, + rootName: string, +): ReadonlyArray { + const { repositories, rootFiles } = turnChanges(checkpoint); + const groups = [ + ...(rootFiles.length === 0 ? [] : [{ key: ".", name: rootName, relativePath: "" }]), + ...repositories.flatMap((repository) => + repository.files.length === 0 || !repository.relativePath || repository.relativePath === "." + ? [] + : [ + { + key: repository.repositoryPath, + name: repository.name, + relativePath: repository.relativePath, + }, + ], + ), + ]; + return groups.length > 1 ? groups : []; } function compareCheckpointTurnCountDescending( @@ -497,7 +531,8 @@ export function getReadyReviewCheckpoints( ): ReadonlyArray { return pipe( checkpoints, - Arr.filter((checkpoint) => checkpoint.status === "ready"), + // A plain folder holding repositories never has a ready checkpoint of its own. + Arr.filter((checkpoint) => checkpoint.status === "ready" || turnHasChanges(checkpoint)), Arr.sort(readyCheckpointOrder), ); } @@ -519,10 +554,16 @@ export function buildReviewSectionItems(input: { readonly gitSections: ReadonlyArray; readonly turnDiffById: Readonly>; readonly loadingGitSections: boolean; + /** Names the thread folder's own files beside its repositories. */ + readonly rootName?: string; }): ReadonlyArray { const turnItems = getReadyReviewCheckpoints(input.checkpoints).map( (checkpoint) => { const id = getReviewSectionIdForCheckpoint(checkpoint); + const repositoryGroups = checkpointRepositoryGroups(checkpoint, input.rootName ?? "Project"); + const unlistedRepositories = (checkpoint.repositories ?? []).flatMap((repository) => + repository.baselineMissing ? [repository.name] : [], + ); return { id, kind: "turn", @@ -530,6 +571,8 @@ export function buildReviewSectionItems(input: { subtitle: checkpointSubtitle(checkpoint), diff: input.turnDiffById[id] ?? null, isLoading: false, + ...(repositoryGroups.length === 0 ? {} : { repositoryGroups }), + ...(unlistedRepositories.length === 0 ? {} : { unlistedRepositories }), }; }, ); @@ -687,3 +730,31 @@ export function applyReviewDiffMetadata( }); return { ...previewDiff, ...totals, files, fileCount: selectedSection.files.length, notice }; } + +/** + * The files of one folder of a turn's patch. A file belongs to the deepest folder holding it, + * and to the thread's own (the empty folder) when no repository does. + */ +export function filterReviewParsedDiffToFolder( + parsedDiff: ReviewParsedDiff, + folder: string, + folders: ReadonlyArray, +): ReviewParsedDiff { + if (parsedDiff.kind !== "files") return parsedDiff; + const files = parsedDiff.files.filter((file) => { + let owner = ""; + for (const candidate of folders) { + if (candidate.length > owner.length && file.path.startsWith(`${candidate}/`)) { + owner = candidate; + } + } + return owner === folder; + }); + return { + ...parsedDiff, + files, + fileCount: files.length, + additions: files.reduce((total, file) => total + file.additions, 0), + deletions: files.reduce((total, file) => total + file.deletions, 0), + }; +} diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index d9ec656cbc773..02815b1644b63 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -7,6 +7,7 @@ import { getCachedReviewParsedDiff } from "./reviewState"; import { applyReviewDiffMetadata, buildReviewParsedDiff, + filterReviewParsedDiffToFolder, type ReviewParsedDiff, type ReviewRenderableFile, type ReviewSectionItem, @@ -128,18 +129,33 @@ export function useReviewDiffData(input: { readonly selectedSection: ReviewSectionItem | null; readonly draftMessage: string; readonly draftContext: OrchestrationMessageContext | undefined; + /** Shows one folder of a turn's patch; `folders` lists every folder, NUL-separated. */ + readonly repositoryFilter: { readonly folder: string; readonly folders: string } | null; }) { const { draftMessage, draftContext, selectedSection, threadKey } = input; const selectedSectionId = selectedSection?.id ?? null; const source = selectedSection?.source; const lazySource = source?.truncated && source.files ? source : null; - const previewDiff: ReviewParsedDiff = lazySource + const sectionDiff: ReviewParsedDiff = lazySource ? { kind: "empty" } : getCachedReviewParsedDiff({ threadKey, sectionId: selectedSection?.id ?? null, diff: selectedSection?.diff, }); + const repositoryFolder = input.repositoryFilter?.folder ?? null; + const repositoryFolders = input.repositoryFilter?.folders ?? ""; + const previewDiff = useMemo( + () => + repositoryFolder === null + ? sectionDiff + : filterReviewParsedDiffToFolder( + sectionDiff, + repositoryFolder, + repositoryFolders.split("\0"), + ), + [sectionDiff, repositoryFolder, repositoryFolders], + ); const registry = useContext(RegistryContext); const { environmentId, cwd } = input; const scope = JSON.stringify([ diff --git a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx index d0fda18cf60cd..30adccfff26dc 100644 --- a/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx +++ b/apps/mobile/src/features/review/useReviewHeaderPresentation.tsx @@ -27,7 +27,7 @@ export function useReviewHeaderPresentation(props: { readonly selectedSection: ReviewSectionItem | null; readonly onRefresh: () => Promise; }): ReviewHeaderPresentation { - const { selectedThread } = useThreadSelection(); + const { selectedThread, selectedThreadProject } = useThreadSelection(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); const gitStatusQuery = useEnvironmentQuery( @@ -45,6 +45,7 @@ export function useReviewHeaderPresentation(props: { environmentId: props.environmentId, threadId: props.threadId, currentBranch: selectedThread?.branch ?? null, + tracksRepositories: (selectedThreadProject?.trackedFolders?.length ?? 0) > 0, gitStatus: gitStatusQuery.data, gitOperationLabel: gitState.gitOperationLabel, onPull: gitActions.onPullSelectedThreadBranch, diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 4fd506732e5d3..bb90e77e27113 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem"; import { Atom } from "effect/reactivity"; +import { useMemo } from "react"; import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts"; @@ -9,10 +10,11 @@ import { useCheckpointDiff } from "../../state/queries"; import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentPresentation } from "../../state/presentation"; import { lastReviewGitSectionsAtom, reviewEnvironment } from "../../state/review"; -import { lastReviewTurnDiffsAtom } from "../../state/reviewTurnDiffs"; +import { lastReviewTurnDiffsAtom, reviewTurnDiffText } from "../../state/reviewTurnDiffs"; import { environmentSession } from "../../state/session"; import { useSelectedThreadProjection } from "../../state/use-thread-detail"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; +import { useThreadSelection } from "../../state/use-thread-selection"; import { buildReviewSectionItems, getReadyReviewCheckpoints, @@ -53,6 +55,7 @@ export function useReviewSections(input: { const { canReadFiles } = fileAccess; const selectedThread = useSelectedThreadProjection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); + const { selectedThreadProject } = useThreadSelection(); const diffPreview = useEnvironmentQuery( canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null ? reviewEnvironment.diffPreview({ @@ -87,6 +90,7 @@ export function useReviewSections(input: { canReadFiles || fileAccess.isPending ? (diffPreview.data?.sources ?? lastGitSections) : [], turnDiffById: reviewTurnDiffsBySectionId(readyCheckpoints, lastTurnDiffs), loadingGitSections: fileAccess.isPending || diffPreview.isPending, + ...(selectedThreadProject ? { rootName: selectedThreadProject.title } : {}), }); const selectedSectionId = resolveReviewSelectedSectionId( cachedSections, @@ -107,13 +111,18 @@ export function useReviewSections(input: { toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null, ignoreWhitespace: false, }); + const activeTurnDiffData = activeTurnDiff.data; + const activeTurnDiffText = useMemo( + () => (activeTurnDiffData == null ? null : reviewTurnDiffText(activeTurnDiffData)), + [activeTurnDiffData], + ); const reviewSections = cachedSections.map((section): ReviewSectionItem => { if (section.kind === "turn") { return section.id === activeSectionId ? { ...section, - diff: activeTurnDiff.data?.diff ?? section.diff, + diff: activeTurnDiffText ?? section.diff, isLoading: activeTurnDiff.isPending, } : section; diff --git a/apps/mobile/src/features/threads/DraftThreadHeader.tsx b/apps/mobile/src/features/threads/DraftThreadHeader.tsx index 043273ee79bec..a07ea2c5d26ff 100644 --- a/apps/mobile/src/features/threads/DraftThreadHeader.tsx +++ b/apps/mobile/src/features/threads/DraftThreadHeader.tsx @@ -55,6 +55,7 @@ export function DraftThreadHeader(props: { environmentId, threadId: props.thread.id, hasThread: false, + tracksRepositories: (props.project.trackedFolders?.length ?? 0) > 0, currentBranch: props.thread.branch, gitStatus: status.data, gitOperationLabel: progress.currentLabel, diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index cffa9134413e9..53b258b05eae3 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -42,6 +42,7 @@ import { } from "@t3tools/client-runtime/user-message"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { turnChanges } from "@t3tools/client-runtime/state/thread-repositories"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { @@ -2380,10 +2381,20 @@ function TurnDiffStat(props: { readonly checkpoint: ThreadCheckpointSummary; readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void; }) { - const { files } = props.checkpoint; - const additions = files.reduce((total, file) => total + file.additions, 0); - const deletions = files.reduce((total, file) => total + file.deletions, 0); - const fileCountLabel = `${files.length} file${files.length === 1 ? "" : "s"} changed`; + const { repositories, rootFiles, totals } = turnChanges(props.checkpoint); + const { additions, deletions } = totals; + const folderCount = repositories.length + (rootFiles.length > 0 ? 1 : 0); + const repositoriesLabel = + repositories.length === 0 + ? null + : folderCount === 1 + ? repositories[0]!.name + : `${folderCount} repos`; + const fileCountLabel = `${totals.count} file${totals.count === 1 ? "" : "s"} changed${ + repositories.length === 0 + ? "" + : ` in ${repositories.map((repository) => repository.name).join(", ")}` + }`; return ( props.onOpenTurnDiff(props.checkpoint)} className="min-h-11 shrink-0 flex-row items-center gap-2 px-2 active:bg-subtle" > + {repositoriesLabel ? ( + + {repositoriesLabel} + + ) : null} +{formatDiffCount(additions)} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 57d26e3b65d0c..f34074006bf93 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -82,6 +82,8 @@ export type ThreadGitMenuProps = { readonly threadId: ThreadId | string; readonly currentBranch: string | null; readonly hasThread?: boolean; + /** The project tracks repositories besides its folder, which then need not be one itself. */ + readonly tracksRepositories?: boolean; readonly gitStatus: VcsStatusResult | null; readonly gitOperationLabel: string | null; readonly onOpenFilesInspector?: () => void; @@ -304,38 +306,46 @@ export function threadTerminalMenu(props: ThreadGitControlsProps): AppBarMenu | /** The thread's git menu, shared by the thread bar and Review. */ export function useThreadGitMenuDefinition(props: ThreadGitMenuProps): AppBarMenu | null { const model = useThreadGitControlModel(props); + // A plain folder that tracks repositories has no branch of its own; its turns still have diffs. + const repositoriesOnly = !model.isRepo && props.tracksRepositories === true; return { title: "Git controls", icon: "point.topleft.down.curvedto.point.bottomright.up", separateBackground: false, items: [ - { - id: "git-status", - title: compactMenuBranchLabel(model.currentBranchLabel), - icon: "point.topleft.down.curvedto.point.bottomright.up", - disabled: true, - subtitle: compactMenuStatus(props.gitStatus), - onPress: () => {}, - }, - { - id: "git-quick-action", - title: model.quickAction.label, - icon: model.quickActionIcon, - disabled: model.quickAction.disabled, - subtitle: model.quickActionHint ?? undefined, - onPress: () => { - void model.runQuickAction(); - }, - }, + ...(repositoriesOnly + ? [] + : [ + { + id: "git-status", + title: compactMenuBranchLabel(model.currentBranchLabel), + icon: "point.topleft.down.curvedto.point.bottomright.up", + disabled: true, + subtitle: compactMenuStatus(props.gitStatus), + onPress: () => {}, + }, + { + id: "git-quick-action", + title: model.quickAction.label, + icon: model.quickActionIcon, + disabled: model.quickAction.disabled, + subtitle: model.quickActionHint ?? undefined, + onPress: () => { + void model.runQuickAction(); + }, + }, + ]), { id: "git-review", title: "Review changes", icon: "text.bubble", - disabled: !model.isRepo || props.hasThread === false, + disabled: !(model.isRepo || repositoriesOnly) || props.hasThread === false, subtitle: props.hasThread === false ? "Available after the first message" - : "Turn diffs and worktree changes", + : repositoriesOnly + ? "Turn diffs" + : "Turn diffs and worktree changes", onPress: model.openReview, }, ...(props.onMergeBack diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 0bed5a25f0271..60e79fdb5150c 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -803,6 +803,7 @@ function ThreadRouteContent( ? () => void handleMergeBack() : undefined, currentBranch: selectedThread?.branch ?? null, + tracksRepositories: (selectedThreadProject?.trackedFolders?.length ?? 0) > 0, gitStatus: gitStatus.data, gitOperationLabel: gitState.gitOperationLabel, canOpenTerminal: diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index c3a591f50ef4b..64fb246a83673 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -96,12 +96,20 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { : null, ); - const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD"; - const currentStatusSummary = statusSummary(gitStatus.data); + const isRepo = gitStatus.data?.isRepo ?? true; + // A plain folder that tracks repositories has no branch of its own; its turns still have diffs. + const trackedRepositoryCount = isRepo ? 0 : (selectedThreadProject?.trackedFolders?.length ?? 0); + const currentBranchLabel = + trackedRepositoryCount > 0 + ? (selectedThreadProject?.title ?? "Repositories") + : (gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD"); + const currentStatusSummary = + trackedRepositoryCount > 0 + ? `${trackedRepositoryCount} tracked ${trackedRepositoryCount === 1 ? "repository" : "repositories"}` + : statusSummary(gitStatus.data); const currentWorktreePath = selectedThreadWorktreePath; const gitOperationLabel = gitState.gitOperationLabel; const busy = gitOperationLabel !== null; - const isRepo = gitStatus.data?.isRepo ?? true; const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false; const isDefaultRef = gitStatus.data?.isDefaultRef ?? false; @@ -268,8 +276,12 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { 0 + ? "Inspect turn diffs" + : "Inspect changes, uncommitted edits, and turn diffs" + } + disabled={busy || !(isRepo || trackedRepositoryCount > 0)} onPress={() => { const params = { environmentId, threadId }; if (presentation === "sheet") { diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 6de60afc1cb26..1cf8a36d68370 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -604,6 +604,25 @@ describe("buildThreadFeed", () => { }); expect(before[1]).not.toHaveProperty("message.checkpointSummary"); expect(getReviewSectionIdForCheckpoint(summary)).toBe("turn:2"); + // A plain folder's own checkpoint is missing every turn; its repositories still changed. + const inRepository = { + ...summary, + status: "missing" as const, + files: [], + repositories: [ + { + scopeId: CheckpointScopeId.make("scope-api"), + name: "api", + repositoryPath: "/work/api", + cwd: "/work/api", + files: summary.files, + baselineMissing: false, + }, + ], + }; + expect(buildThreadFeed(rows, { checkpointSummaries: [inRepository] })[1]).toMatchObject({ + message: { checkpointSummary: inRepository }, + }); const fallback = deriveThreadFeedPresentation( [after.at(-1)!], null, diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 5b9f07ed77332..99e2c4ca1d454 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -5,6 +5,7 @@ import type { import { linkRequestTargetName } from "@t3tools/client-runtime/link-request"; import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories"; import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { isLiveSubagentTurnItem, @@ -2291,6 +2292,7 @@ function checkpointSummariesEqual( summary.completedAt === other.completedAt && summary.status === other.status && summary.files === other.files && + summary.repositories === other.repositories && summary.assistantMessageId === other.assistantMessageId ); }); @@ -2576,7 +2578,12 @@ export function buildThreadFeed( } const checkpointByMessageId = new Map( (options?.checkpointSummaries ?? []) - .filter((checkpoint) => checkpoint.status === "ready" && checkpoint.files.length > 0) + // A plain folder holding repositories never has a ready checkpoint of its own. + .filter( + (checkpoint) => + (checkpoint.status === "ready" || checkpoint.repositories !== undefined) && + turnHasChanges(checkpoint), + ) .map((checkpoint) => [checkpoint.assistantMessageId, checkpoint]), ); const grouped = groupAdjacentActivities( diff --git a/apps/mobile/src/state/reviewTurnDiffs.test.ts b/apps/mobile/src/state/reviewTurnDiffs.test.ts index 9fea5264428d2..a7c713ac9f4d0 100644 --- a/apps/mobile/src/state/reviewTurnDiffs.test.ts +++ b/apps/mobile/src/state/reviewTurnDiffs.test.ts @@ -3,8 +3,12 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { AtomRegistry } from "effect/reactivity"; -import { reviewTurnDiffsBySectionId } from "../features/review/reviewModel"; -import { lastReviewTurnDiffsAtom, recordReviewTurnDiffAnswer } from "./reviewTurnDiffs"; +import { buildReviewParsedDiff, reviewTurnDiffsBySectionId } from "../features/review/reviewModel"; +import { + lastReviewTurnDiffsAtom, + recordReviewTurnDiffAnswer, + reviewTurnDiffText, +} from "./reviewTurnDiffs"; const environmentId = EnvironmentId.make("env-1"); const threadId = ThreadId.make("thread-1"); @@ -20,6 +24,79 @@ const answer = ( registry, ); +const modified = (path: string, line: string) => + [ + `diff --git a/${path} b/${path}`, + "index 1111111..2222222 100644", + `--- a/${path}`, + `+++ b/${path}`, + "@@ -1 +1,2 @@", + " const before = 1;", + `+${line}`, + "", + ].join("\n"); + +describe("reviewTurnDiffText", () => { + it("leaves a thread without repositories its one patch", () => { + const diff = modified("src/index.ts", "const root = 1;"); + expect(reviewTurnDiffText({ diff })).toBe(diff); + expect(reviewTurnDiffText({ diff, repositories: [] })).toBe(diff); + }); + + it("names each repository's files from the thread's folder", () => { + const text = reviewTurnDiffText({ + diff: "", + repositories: [ + { + name: "api", + repositoryPath: "/work/api", + relativePath: "api", + diff: [ + modified("src/index.ts", "--- a/not-a-header"), + "diff --git a/added.ts b/added.ts", + "new file mode 100644", + "index 0000000..2222222", + "--- /dev/null", + "+++ b/added.ts", + "@@ -0,0 +1 @@", + "+export {};", + "diff --git a/old name.ts b/new name.ts", + "similarity index 100%", + "rename from old name.ts", + "rename to new name.ts", + "", + ].join("\n"), + }, + { + name: "web", + repositoryPath: "/elsewhere/web", + relativePath: "../elsewhere/web", + diff: `${modified("src/index.ts", "const web = 1;")}\n[truncated]`, + }, + ], + }); + + expect(text).toContain("+--- a/not-a-header\n"); + expect(text).toContain("rename from api/old name.ts\nrename to api/new name.ts\n"); + expect(text.endsWith("\n\n[truncated]")).toBe(true); + const complete = buildReviewParsedDiff(text.replace("[truncated]", ""), "unit-repositories"); + expect(complete.kind === "files" && complete.files.map((file) => file.path)).toEqual([ + "api/src/index.ts", + "api/added.ts", + "api/new name.ts", + "../elsewhere/web/src/index.ts", + ]); + expect( + complete.kind === "files" && complete.files[1]?.completePatchSource?.().newContents, + ).toBe("export {};\n"); + expect(buildReviewParsedDiff(text, "unit-repositories-truncated")).toMatchObject({ + kind: "files", + fileCount: 4, + notice: expect.stringContaining("server size cap"), + }); + }); +}); + describe("recordReviewTurnDiffAnswer", () => { it.effect("keeps loaded turn diffs for review after their queries are gone", () => Effect.gen(function* () { diff --git a/apps/mobile/src/state/reviewTurnDiffs.ts b/apps/mobile/src/state/reviewTurnDiffs.ts index 1816ade56f3a9..488dbee5a52b2 100644 --- a/apps/mobile/src/state/reviewTurnDiffs.ts +++ b/apps/mobile/src/state/reviewTurnDiffs.ts @@ -1,7 +1,99 @@ +import { turnDiffSections } from "@t3tools/client-runtime/state/thread-repositories"; import type { EnvironmentId, OrchestrationGetTurnDiffResult, ThreadId } from "@t3tools/contracts"; +import { quoteGitPatchPath, unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import * as Effect from "effect/Effect"; import { Atom, type AtomRegistry } from "effect/reactivity"; +const TRUNCATION_MARKER = /(?:\r?\n){1,2}\[truncated\]\s*$/; +const QUOTED_PATH = String.raw`"(?:[^"\\]|\\.)*"`; +const GIT_HEADER_PATHS = new RegExp(`^(${QUOTED_PATH}|a/.*?) (${QUOTED_PATH}|b/.*)$`); +const BINARY_FILES = new RegExp( + `^Binary files (${QUOTED_PATH}|.+?) and (${QUOTED_PATH}|.+) differ$`, +); +const HEADER_PATH_LINES = [ + ["--- ", "a/"], + ["+++ ", "b/"], + ["rename from ", ""], + ["rename to ", ""], + ["copy from ", ""], + ["copy to ", ""], +] as const; + +function pathInFolder(token: string, folder: string, side: "a/" | "b/" | ""): string { + const quoted = token.length >= 2 && token.startsWith('"') && token.endsWith('"'); + const path = quoted ? unquoteGitPatchPath(token) : token; + if (path === "/dev/null" || !path.startsWith(side)) return token; + return quoteGitPatchPath(`${side}${folder}/${path.slice(side.length)}`); +} + +function gitHeaderPaths(paths: string): readonly [string, string] | null { + // An unchanged name is repeated, which settles where a name holding " b/" ends. + const middle = (paths.length - 1) / 2; + if ( + Number.isInteger(middle) && + paths.startsWith("a/") && + paths.startsWith(" b/", middle) && + paths.slice(2, middle) === paths.slice(middle + 3) + ) { + return [paths.slice(0, middle), paths.slice(middle + 1)]; + } + const match = GIT_HEADER_PATHS.exec(paths); + return match ? [match[1]!, match[2]!] : null; +} + +function patchInFolder(patch: string, folder: string): string { + let inHeader = false; + return patch + .split("\n") + .map((line) => { + if (line.startsWith("diff --git ")) { + inHeader = true; + const paths = gitHeaderPaths(line.slice("diff --git ".length)); + return paths === null + ? line + : `diff --git ${pathInFolder(paths[0], folder, "a/")} ${pathInFolder(paths[1], folder, "b/")}`; + } + if (!inHeader) return line; + if (line.startsWith("@@") || line === "GIT binary patch") { + inHeader = false; + return line; + } + for (const [lead, side] of HEADER_PATH_LINES) { + if (!line.startsWith(lead)) continue; + const tab = line.endsWith("\t") ? "\t" : ""; + const token = line.slice(lead.length, line.length - tab.length); + return `${lead}${pathInFolder(token, folder, side)}${tab}`; + } + const binary = BINARY_FILES.exec(line); + return binary + ? `Binary files ${pathInFolder(binary[1]!, folder, "a/")} and ${pathInFolder(binary[2]!, folder, "b/")} differ` + : line; + }) + .join("\n"); +} + +/** + * A turn diff as the one patch review shows. Each tracked repository's files are renamed from + * the thread's folder, so the same path in two repositories stays two files and a review comment + * names a path the agent can open. + */ +export function reviewTurnDiffText(diff: Parameters[0]): string { + const sections = turnDiffSections(diff, ""); + if (sections.every((section) => section.repositoryPath === null)) return diff.diff; + let truncated = false; + const patches = sections.map((section) => { + const marker = TRUNCATION_MARKER.exec(section.diff); + truncated ||= marker !== null; + const text = marker === null ? section.diff : section.diff.slice(0, marker.index); + const patch = + section.relativePath === "" || section.relativePath === "." + ? text + : patchInFolder(text, section.relativePath); + return patch.endsWith("\n") ? patch : `${patch}\n`; + }); + return `${patches.join("")}${truncated ? "\n[truncated]" : ""}`; +} + const EMPTY_TURN_DIFFS = Object.freeze>>({}); // The last answered diff of each single turn, keyed by its turn count, so review keeps showing @@ -33,6 +125,7 @@ export const recordReviewTurnDiffAnswer = ( } const atom = lastReviewTurnDiffsAtom(target.environmentId, value.threadId); const current = registry.get(atom); - if (current[value.toTurnCount] === value.diff) return; - registry.set(atom, { ...current, [value.toTurnCount]: value.diff }); + const diff = reviewTurnDiffText(value); + if (current[value.toTurnCount] === diff) return; + registry.set(atom, { ...current, [value.toTurnCount]: diff }); }); diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index 7c516e97fa730..4fe6133cefcc7 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -64,7 +64,7 @@ function layerFor(input: { }), ), ), - Layer.provideMerge(NodeCrypto.layer), + Layer.provideMerge(Layer.merge(NodeCrypto.layer, NodeServices.layer)), ); } @@ -319,6 +319,8 @@ it.effect("truncates a storage-cut UTF-8 character without replacement text", () const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 }); assert.isAtMost(Buffer.byteLength(result.diff), 10_000_000); assert.isTrue(result.diff === `${prefix}\n\n[truncated]`); + // A thread without tracked repositories keeps the payload it always had. + assert.notProperty(result, "repositories"); }).pipe(Effect.provide(layer)); }); @@ -343,3 +345,64 @@ it.effect("preserves an exact-fit filtered patch across batches without a marker assert.strictEqual(patchReads, 2); }).pipe(Effect.provide(layer)); }); + +it.effect("adds a patch for each tracked repository that changed in the range", () => { + const projection = makeProjection(); + const repository = (name: string, cwd: string, ordinals: ReadonlyArray) => { + const id = CheckpointScopeId.make(`scope:checkpoint-diff-v2:${name}`); + return { + scope: { + id, + runId: firstRunId, + kind: "manual" as const, + cwd, + label: name, + repositoryPath: cwd, + }, + checkpoints: ordinals.map((ordinalWithinScope) => ({ + scopeId: id, + runId: ordinalWithinScope === 2 ? secondRunId : null, + ordinalWithinScope, + appRunOrdinal: null, + status: "ready" as const, + ref: CheckpointRef.make(`refs/t3/test/${name}/${ordinalWithinScope}`), + })), + }; + }; + const sibling = repository("shared", "/work/shared", [1, 2]); + // Nothing before the range's end, so there is no patch to make. + const nested = repository("ui", "/work/app/packages/ui", [2]); + const diffCheckpoints = vi.fn((input: CheckpointStore.DiffCheckpointsInput) => + Effect.succeed(input.format === "numstat" ? "1\t0\tfile.ts\0" : `patch of ${input.cwd}`), + ); + const layer = layerFor({ + projection: Effect.succeed({ + ...projection, + checkpointScopes: [ + ...projection.checkpointScopes.map((scope) => ({ ...scope, cwd: "/work/app" })), + sibling.scope, + nested.scope, + ], + checkpoints: [...projection.checkpoints, ...sibling.checkpoints, ...nested.checkpoints], + }), + diffCheckpoints, + }); + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 }); + assert.deepEqual(result.repositories, [ + { + name: "shared", + repositoryPath: "/work/shared", + relativePath: "../shared", + diff: "patch of /work/shared", + }, + ]); + // The thread's own patch leaves the folder of the repository inside it alone. + assert.strictEqual(result.diff, "patch of /work/app"); + assert.deepEqual( + diffCheckpoints.mock.calls.find(([input]) => input.cwd === "/work/app")?.[0].excludePaths, + ["packages/ui"], + ); + }).pipe(Effect.provide(layer)); +}); diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index bf9543919de65..119f9e33deaeb 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -1,20 +1,28 @@ import { CHECKPOINT_DIFF_TRUNCATED_MARKER, + type CheckpointRef, OrchestrationGetTurnDiffResult, type OrchestrationGetFullThreadDiffInput, type OrchestrationGetFullThreadDiffResult, type OrchestrationGetTurnDiffInput, type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType, type ThreadId, + type ThreadTurnRepositoryDiff, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { CHECKPOINT_DIFF_MAX_OUTPUT_BYTES } from "../vcs/VcsDriver.ts"; -import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts"; +import { + checkpointRefForScopeOrdinal, + nestedScopePaths, +} from "../orchestration-v2/CheckpointService.ts"; +import type { ProjectionCheckpointContext } from "../orchestration-v2/ProjectionStore.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import { CheckpointDiffResultInvalidError, @@ -29,6 +37,7 @@ import { isGitImport, parseTurnDiffFilesFromNumstat, type TurnDiffFileSummary } // Windows limits a command line to 32,767 characters. Leave room for the rest of git's arguments. const MAX_PATHSPEC_CHARS = 24_000; +const REPOSITORY_DIFF_CONCURRENCY = 6; function batchFilePaths(files: ReadonlyArray) { const batches: string[][] = []; @@ -71,20 +80,176 @@ function buildTurnDiffResult( readonly toTurnCount: number; }, diff: string, + repositories?: ReadonlyArray, ): OrchestrationGetTurnDiffResultType { return { threadId: input.threadId, fromTurnCount: input.fromTurnCount, toTurnCount: input.toTurnCount, diff, + ...(repositories === undefined ? {} : { repositories }), }; } +type ContextCheckpoint = ProjectionCheckpointContext["checkpoints"][number]; + +/** + * A repository's checkpoints for a turn range. Only turns that changed it are recorded, each with + * the baseline before it, so the range runs from its first record to its last one inside the + * range. None when no turn in the range changed it. + */ +function repositoryDiffRange( + checkpoints: ReadonlyArray, + range: { readonly fromTurnCount: number; readonly toTurnCount: number }, +): { readonly from: ContextCheckpoint; readonly to: ContextCheckpoint } | undefined { + const ready = checkpoints + .filter( + (checkpoint) => + checkpoint.status === "ready" && + checkpoint.ordinalWithinScope >= range.fromTurnCount && + checkpoint.ordinalWithinScope <= range.toTurnCount, + ) + .toSorted((left, right) => left.ordinalWithinScope - right.ordinalWithinScope); + const from = ready[0]; + const to = ready.at(-1); + return from === undefined || to === undefined || from === to ? undefined : { from, to }; +} + /** @public */ export const make = Effect.gen(function* () { const threads = yield* ThreadManagement.ThreadManagementService; const checkpointStore = yield* CheckpointStore.CheckpointStore; const digest = yield* Digest.Digest; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + interface Comparison { + readonly cwd: string; + readonly fromCheckpointRef: CheckpointRef; + readonly toCheckpointRef: CheckpointRef; + readonly fallbackFromToHead: false; + readonly ignoreWhitespace: boolean; + readonly excludePaths?: ReadonlyArray; + } + + // What a pull or rebase brought in is not the turn's work. Null keeps every changed file. + const retainedFilePaths = Effect.fn("CheckpointDiffQuery.retainedFilePaths")(function* ( + comparison: Comparison, + ) { + const authoredPaths = yield* checkpointStore + .listAuthoredPaths(comparison) + .pipe(Effect.orElseSucceed(() => null)); + const files = + authoredPaths === null + ? [] + : yield* checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe( + Effect.map(parseTurnDiffFilesFromNumstat), + Effect.orElseSucceed(() => []), + ); + const retainedFiles = files.filter((file) => !isGitImport(file, authoredPaths)); + return retainedFiles.length === files.length ? null : retainedFiles; + }); + + // Selects retained paths before generating a patch, so imported bulk cannot exhaust the limit. + const patchBetween = Effect.fn("CheckpointDiffQuery.patchBetween")(function* ( + comparison: Comparison, + maxBytes: number, + ) { + const retainedFiles = yield* retainedFilePaths(comparison); + const pathBatches = retainedFiles === null ? [undefined] : batchFilePaths(retainedFiles); + let diff = ""; + let remainingBytes = maxBytes; + for (const filePaths of pathBatches) { + const patch = yield* checkpointStore + .diffCheckpoints({ + ...comparison, + ...(filePaths === undefined ? {} : { filePaths }), + // One extra byte distinguishes an exact fit from a truncated patch. + maxOutputBytes: remainingBytes + 1, + }) + .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints")); + const patchBytes = Buffer.byteLength(patch); + diff += patch; + if (patchBytes > remainingBytes) { + // Reserve marker space only on overflow, which may trim an earlier batch. + // Streaming decode drops an incomplete final UTF-8 character at the byte boundary. + diff = + new TextDecoder().decode( + Buffer.from(diff).subarray( + 0, + Math.max(0, maxBytes - Buffer.byteLength(CHECKPOINT_DIFF_TRUNCATED_MARKER)), + ), + { stream: true }, + ) + CHECKPOINT_DIFF_TRUNCATED_MARKER; + break; + } + remainingBytes -= patchBytes; + } + return diff; + }); + + // Most tracked repositories are untouched in a turn. A numstat finds the few that changed + // before any patch is built, and those patches then share what the thread's own patch left. + const repositoryDiffs = Effect.fn("CheckpointDiffQuery.repositoryDiffs")(function* (input: { + readonly projection: ProjectionCheckpointContext; + readonly threadCwd: string; + readonly fromTurnCount: number; + readonly toTurnCount: number; + readonly ignoreWhitespace: boolean; + readonly nested: ReadonlyMap>; + readonly maxBytes: number; + }) { + const changed = yield* Effect.forEach( + input.projection.checkpointScopes.filter((scope) => typeof scope.repositoryPath === "string"), + (scope) => { + const range = repositoryDiffRange( + input.projection.checkpoints.filter((checkpoint) => checkpoint.scopeId === scope.id), + input, + ); + if (range === undefined) return Effect.succeed([]); + const excludePaths = input.nested.get(scope.id); + const comparison: Comparison = { + cwd: scope.cwd, + fromCheckpointRef: range.from.ref, + toCheckpointRef: range.to.ref, + fallbackFromToHead: false, + ignoreWhitespace: input.ignoreWhitespace, + ...(excludePaths === undefined ? {} : { excludePaths }), + }; + return checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe( + Effect.map((numstat) => (numstat === "" ? [] : [{ scope, comparison }])), + Effect.catch((cause) => + Effect.logWarning("checkpoint repository diff unavailable", { + scopeId: scope.id, + cause: String(cause), + }).pipe(Effect.as([])), + ), + ); + }, + { concurrency: REPOSITORY_DIFF_CONCURRENCY }, + ); + const repositories: Array = []; + let remainingBytes = input.maxBytes; + for (const { scope, comparison } of changed.flat()) { + const diff = yield* patchBetween(comparison, remainingBytes).pipe( + Effect.catch((cause) => + Effect.logWarning("checkpoint repository diff unavailable", { + scopeId: scope.id, + cause: String(cause), + }).pipe(Effect.as("")), + ), + ); + if (diff === "") continue; + remainingBytes = Math.max(0, remainingBytes - Buffer.byteLength(diff)); + repositories.push({ + name: scope.label ?? path.basename(scope.cwd), + repositoryPath: scope.repositoryPath ?? scope.cwd, + relativePath: path.relative(input.threadCwd, scope.cwd).split(path.sep).join("/"), + diff, + }); + } + return repositories; + }); const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")( function* (input) { @@ -121,14 +286,22 @@ export const make = Effect.gen(function* () { const completedRunIds = new Set( projection.runs.filter((run) => run.status === "completed").map((run) => run.id), ); - const readyCheckpoints = projection.checkpoints.filter( + const hasRepositories = projection.checkpointScopes.some( + (scope) => typeof scope.repositoryPath === "string", + ); + // A thread folder that is not a Git repository records missing checkpoints; its turns still + // exist for the repositories inside it. + const turnCheckpoints = projection.checkpoints.filter( (checkpoint) => - checkpoint.status === "ready" && + (checkpoint.status === "ready" || (hasRepositories && checkpoint.status === "missing")) && checkpoint.appRunOrdinal !== null && checkpoint.runId !== null && completedRunIds.has(checkpoint.runId), ); - const maxTurnCount = readyCheckpoints.reduce( + const readyCheckpoints = turnCheckpoints.filter( + (checkpoint) => checkpoint.status === "ready", + ); + const maxTurnCount = turnCheckpoints.reduce( (max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0), 0, ); @@ -141,7 +314,7 @@ export const make = Effect.gen(function* () { }); } - const toCheckpoint = readyCheckpoints.find( + const toCheckpoint = turnCheckpoints.find( (checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount, ); if (toCheckpoint === undefined) { @@ -163,6 +336,41 @@ export const make = Effect.gen(function* () { }); } + const nested = hasRepositories + ? yield* nestedScopePaths([ + toScope, + ...projection.checkpointScopes.filter( + (scope) => typeof scope.repositoryPath === "string", + ), + ]).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ) + : undefined; + const withRepositories = Effect.fnUntraced(function* (diff: string) { + const repositories = + nested === undefined + ? undefined + : yield* repositoryDiffs({ + projection, + threadCwd: toScope.cwd, + fromTurnCount: input.fromTurnCount, + toTurnCount: input.toTurnCount, + ignoreWhitespace, + nested, + maxBytes: Math.max(0, CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - Buffer.byteLength(diff)), + }); + const turnDiff = buildTurnDiffResult(input, diff, repositories); + if (!isTurnDiffResult(turnDiff)) { + return yield* new CheckpointDiffResultInvalidError({ + operation, + threadId: input.threadId, + }); + } + return turnDiff; + }); + if (toCheckpoint.status === "missing") return yield* withRepositories(""); + // Capture compares against the preceding scope ordinal, even when that // checkpoint belongs to a stopped run or has no run. const parentCheckpoint = @@ -202,66 +410,19 @@ export const make = Effect.gen(function* () { }); } - const comparison = { - cwd: toScope.cwd, - fromCheckpointRef, - toCheckpointRef: toCheckpoint.ref, - fallbackFromToHead: false, - ignoreWhitespace, - }; - const authoredPaths = yield* checkpointStore - .listAuthoredPaths(comparison) - .pipe(Effect.orElseSucceed(() => null)); - const files = - authoredPaths === null - ? [] - : yield* checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe( - Effect.map(parseTurnDiffFilesFromNumstat), - Effect.orElseSucceed(() => []), - ); - const retainedFiles = files.filter((file) => !isGitImport(file, authoredPaths)); - // Select retained paths before generating a patch, so imported bulk cannot exhaust its output limit. - const pathBatches = - retainedFiles.length === files.length ? [undefined] : batchFilePaths(retainedFiles); - let diff = ""; - let remainingBytes = CHECKPOINT_DIFF_MAX_OUTPUT_BYTES; - for (const filePaths of pathBatches) { - const patch = yield* checkpointStore - .diffCheckpoints({ - ...comparison, - ...(filePaths === undefined ? {} : { filePaths }), - // One extra byte distinguishes an exact fit from a truncated patch. - maxOutputBytes: remainingBytes + 1, - }) - .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints")); - const patchBytes = Buffer.byteLength(patch); - diff += patch; - if (patchBytes > remainingBytes) { - // Reserve marker space only on overflow, which may trim an earlier batch. - // Streaming decode drops an incomplete final UTF-8 character at the byte boundary. - diff = - new TextDecoder().decode( - Buffer.from(diff).subarray( - 0, - CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - - Buffer.byteLength(CHECKPOINT_DIFF_TRUNCATED_MARKER), - ), - { stream: true }, - ) + CHECKPOINT_DIFF_TRUNCATED_MARKER; - break; - } - remainingBytes -= patchBytes; - } - - const turnDiff = buildTurnDiffResult(input, diff); - if (!isTurnDiffResult(turnDiff)) { - return yield* new CheckpointDiffResultInvalidError({ - operation, - threadId: input.threadId, - }); - } - - return turnDiff; + const excludePaths = nested?.get(toScope.id); + const diff = yield* patchBetween( + { + cwd: toScope.cwd, + fromCheckpointRef, + toCheckpointRef: toCheckpoint.ref, + fallbackFromToHead: false, + ignoreWhitespace, + ...(excludePaths === undefined ? {} : { excludePaths }), + }, + CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + ); + return yield* withRepositories(diff); }, ); diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 15fa9205dee21..7b2667be6d2c1 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -698,4 +698,99 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { }), ); }); + + describe("captureCheckpoint", () => { + it.effect("leaves nested checkouts that have their own checkpoints out of a capture", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const checkpointStore = yield* CheckpointStore.CheckpointStore; + yield* initRepoWithCommit(tmp); + yield* writeTextFile(NodePath.join(tmp, ".gitignore"), "ignored-clone/\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "ignore a clone"]); + const fileSystem = yield* FileSystem.FileSystem; + for (const clone of ["plain-clone", "ignored-clone"]) { + yield* fileSystem.makeDirectory(NodePath.join(tmp, clone)); + yield* initRepoWithCommit(NodePath.join(tmp, clone)); + } + const refs = { + fromCheckpointRef: CheckpointRef.make("refs/t3/test/nested/0"), + toCheckpointRef: CheckpointRef.make("refs/t3/test/nested/1"), + }; + // Captured before the clone was tracked, so this snapshot holds it as a gitlink. + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: refs.fromCheckpointRef, + }); + const excludePaths = ["plain-clone", "ignored-clone"]; + yield* writeTextFile(NodePath.join(tmp, "README.md"), "# changed\n"); + yield* writeTextFile(NodePath.join(tmp, "plain-clone", "README.md"), "# clone edit\n"); + yield* git(NodePath.join(tmp, "plain-clone"), ["commit", "-am", "clone commit"]); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: refs.toCheckpointRef, + excludePaths, + }); + + expect(yield* git(tmp, ["ls-tree", "-r", "--name-only", refs.toCheckpointRef])).toBe( + ".gitignore\nREADME.md", + ); + const diff = { cwd: tmp, ...refs, ignoreWhitespace: false, format: "numstat" as const }; + expect( + parseTurnDiffFilesFromNumstat( + yield* checkpointStore.diffCheckpoints({ ...diff, excludePaths }), + ).map((file) => file.path), + ).toEqual(["README.md"]); + expect( + parseTurnDiffFilesFromNumstat(yield* checkpointStore.diffCheckpoints(diff)).map( + (file) => file.path, + ), + ).toEqual(["plain-clone", "README.md"]); + }), + ); + + it.effect("reads a folder as clean only when nothing in it differs from HEAD", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const checkpointStore = yield* CheckpointStore.CheckpointStore; + yield* initRepoWithCommit(tmp); + yield* writeTextFile(NodePath.join(tmp, "pinned.txt"), "committed\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "pinned"]); + const head = yield* git(tmp, ["rev-parse", "HEAD"]); + + expect(yield* checkpointStore.resolveCleanHead(tmp)).toBe(head); + const checkpointRef = CheckpointRef.make("refs/t3/test/clean/head"); + yield* checkpointStore.captureHeadCheckpoint({ cwd: tmp, checkpointRef, head, seenAt: 1 }); + expect(yield* git(tmp, ["ls-tree", "-r", checkpointRef])).toBe( + yield* git(tmp, ["ls-tree", "-r", "HEAD"]), + ); + // HEAD is the parent and the date is when the folder was seen, as authored paths expect. + expect(yield* git(tmp, ["log", "-1", "--format=%P %ct", checkpointRef])).toBe(`${head} 1`); + + yield* writeTextFile(NodePath.join(tmp, "untracked.txt"), "new\n"); + expect(yield* checkpointStore.resolveCleanHead(tmp)).toBeNull(); + yield* git(tmp, ["clean", "-fd"]); + expect(yield* checkpointStore.resolveCleanHead(tmp)).toBe(head); + // Status does not report an edit behind this flag; a capture would still record it. + yield* git(tmp, ["update-index", "--assume-unchanged", "pinned.txt"]); + yield* writeTextFile(NodePath.join(tmp, "pinned.txt"), "edited behind the flag\n"); + expect(yield* checkpointStore.resolveCleanHead(tmp)).toBeNull(); + + // A commit after the folder was seen is the turn's own, however early that date is. + yield* writeTextFile(NodePath.join(tmp, "later.txt"), "later\n"); + yield* git(tmp, ["add", "later.txt"]); + yield* git(tmp, ["commit", "-m", "later"], { committedAt: "@1000 +0000" }); + const toCheckpointRef = CheckpointRef.make("refs/t3/test/clean/after"); + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef }); + expect( + yield* checkpointStore.listAuthoredPaths({ + cwd: tmp, + fromCheckpointRef: checkpointRef, + toCheckpointRef, + }), + ).toContain("later.txt"); + }), + ); + }); }); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index 8eadf2b5342af..15211333ab1a7 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -12,6 +12,20 @@ export interface CaptureCheckpointInput { readonly checkpointRef: CheckpointRef; /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */ readonly previousCheckpointRef?: CheckpointRef; + /** Folders below `cwd` (relative, `/`-separated) that have their own checkpoints. */ + readonly excludePaths?: ReadonlyArray; +} + +export interface CaptureHeadCheckpointInput { + readonly cwd: string; + readonly checkpointRef: CheckpointRef; + /** A commit `resolveCleanHead` returned for this folder. */ + readonly head: string; + /** + * When the folder was seen clean, in epoch seconds, if that was earlier than now. Commits made + * after a checkpoint count as the turn's own work, so a late snapshot must not postdate them. + */ + readonly seenAt?: number; } export interface RestoreCheckpointInput { @@ -31,6 +45,8 @@ export interface DiffCheckpointsInput { readonly maxOutputBytes?: number; /** Limits the diff to these exact paths. An empty list yields an empty diff. */ readonly filePaths?: ReadonlyArray; + /** Folders below `cwd` left out of the diff, as in a capture. */ + readonly excludePaths?: ReadonlyArray; } export interface ListAuthoredPathsInput { @@ -53,6 +69,17 @@ export class CheckpointStore extends Context.Service< input: CaptureCheckpointInput, ) => Effect.Effect; + /** + * HEAD's commit when the folder matches it exactly: nothing staged, modified or untracked. + * Null otherwise. One status, where a capture stages the whole worktree. + */ + readonly resolveCleanHead: (cwd: string) => Effect.Effect; + + /** Snapshots a folder that was clean at `head` from that commit, without reading its files. */ + readonly captureHeadCheckpoint: ( + input: CaptureHeadCheckpointInput, + ) => Effect.Effect; + readonly hasCheckpointRef: ( input: Omit, ) => Effect.Effect; @@ -103,6 +130,20 @@ export const make = Effect.gen(function* () { return yield* checkpoints.captureCheckpoint(input); }); + const resolveCleanHead: CheckpointStore["Service"]["resolveCleanHead"] = Effect.fn( + "CheckpointStore.resolveCleanHead", + )(function* (cwd) { + const checkpoints = yield* resolveCheckpoints(cwd); + return yield* checkpoints.resolveCleanHead(cwd); + }); + + const captureHeadCheckpoint: CheckpointStore["Service"]["captureHeadCheckpoint"] = Effect.fn( + "CheckpointStore.captureHeadCheckpoint", + )(function* (input) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.captureHeadCheckpoint(input); + }); + const hasCheckpointRef: CheckpointStore["Service"]["hasCheckpointRef"] = Effect.fn( "hasCheckpointRef", )(function* (input) { @@ -141,6 +182,8 @@ export const make = Effect.gen(function* () { return CheckpointStore.of({ isGitRepository, captureCheckpoint, + resolveCleanHead, + captureHeadCheckpoint, hasCheckpointRef, restoreCheckpoint, diffCheckpoints, diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index 828d438646cdf..af276de7ff276 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -1,4 +1,5 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { CheckpointId, @@ -18,24 +19,40 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as CheckpointDiffQuery from "../checkpointing/CheckpointDiffQuery.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; import { VcsProcessTimeoutError } from "@t3tools/contracts"; import * as CheckpointService from "./CheckpointService.ts"; import * as CheckpointCaptureService from "./CheckpointCaptureService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ThreadManagement from "./ThreadManagementService.ts"; +import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; const layerProjectionStoreTest = Layer.mergeAll( ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), SqlitePersistence.layerMemory, ); +const layerNoTrackedFolders = Layer.merge( + NodeServices.layer, + Layer.mock(WorkspaceFolders.WorkspaceFolders)({ + forThread: () => Effect.succeed({ folders: [], extraRoots: [] }), + submodules: () => Effect.succeed([]), + }), +); + const threadId = ThreadId.make("thread:checkpoint-capture-delegated"); const projectId = ProjectId.make("project:checkpoint-capture-delegated"); const runId = RunId.make("run:checkpoint-capture-delegated"); @@ -275,6 +292,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, NodeCrypto.layer, + layerNoTrackedFolders, Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), isGitRepository: () => Effect.succeed(true), @@ -293,6 +311,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { ), ) : Layer.mock(CheckpointService.CheckpointServiceV2)({ + repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die( "baseline materialization must be skipped when ordinal 0 is ready", @@ -449,6 +468,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ + repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die("a discarded run has no baseline"), capture: () => Effect.die("a discarded run must not be captured"), }), @@ -639,6 +659,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, NodeCrypto.layer, + layerNoTrackedFolders, Layer.mock(CheckpointStore.CheckpointStore)({ isGitRepository: () => Effect.succeed(true), hasCheckpointRef: () => Effect.succeed(true), @@ -871,6 +892,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ + repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die("baseline materialization must be skipped when ordinal 0 is ready"), capture: () => Effect.succeed(captured), @@ -1084,6 +1106,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, NodeCrypto.layer, + layerNoTrackedFolders, Layer.mock(CheckpointStore.CheckpointStore)({ isGitRepository: gitUnavailable, captureCheckpoint: gitUnavailable, @@ -1120,4 +1143,509 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { assert.equal(checkpoint?.status, "missing"); }), ); + + // A thread on real Git checkouts: `folders` is what the project tracks, read at each turn. + const withTrackedRepositories = ( + name: string, + use: (context: { + readonly root: string; + readonly folders: Ref.Ref>; + readonly git: (cwd: string, ...args: ReadonlyArray) => Effect.Effect; + readonly initRepository: (cwd: string) => Effect.Effect; + readonly write: (file: string, contents: string) => Effect.Effect; + /** Runs one turn: baseline, the turn's edits, then the capture. Returns what it committed. */ + readonly turn: ( + ordinal: number, + edits: Effect.Effect, + ) => Effect.Effect< + ReadonlyArray<{ + readonly type: string; + readonly label: string; + readonly ordinal?: number; + readonly run?: boolean; + readonly status?: string; + readonly files?: ReadonlyArray; + }> + >; + readonly capture: (ordinal: number) => Effect.Effect; + readonly commits: Ref.Ref; + readonly threadId: ThreadId; + readonly ids: IdAllocator.IdAllocatorV2["Service"]; + readonly diffs: CheckpointDiffQuery.CheckpointDiffQuery["Service"]; + }) => Effect.Effect, + ) => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const repositoryThreadId = ThreadId.make(`thread:${name}`); + const repositoryRootScopeId = CheckpointScopeId.make(`scope:${name}:root`); + const repositoryProviderThreadId = ProviderThreadId.make(`provider-thread:${name}`); + const folders = yield* Ref.make>([]); + const commits = yield* Ref.make(0); + const labels = new Map([[repositoryRootScopeId, "root"]]); + const committed = yield* Ref.make>([]); + const layerNode = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer); + const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(layerNode)); + const layerCheckpointStore = CheckpointStore.layer.pipe( + Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))), + Layer.provide(layerNode), + ); + const layerCheckpointService = CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + layerNode, + layerCheckpointStore, + Layer.mock(WorkspaceFolders.WorkspaceFolders)({ + forThread: () => + Ref.get(folders).pipe( + Effect.map((current) => ({ folders: current, extraRoots: [] })), + ), + submodules: () => Effect.succeed([]), + }), + ), + ), + ); + const layer = Layer.mergeAll( + IdAllocator.layer, + layerNode, + layerVcsProcess, + layerCheckpointService, + CheckpointCaptureService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + layerCheckpointService, + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => + Effect.forEach(input.events, (event) => projectionStore.apply(event)).pipe( + Effect.andThen(Ref.set(committed, input.events)), + Effect.andThen(Ref.update(commits, (count) => count + 1)), + Effect.as({ committed: true } as never), + Effect.orDie, + ), + }), + ), + ), + ), + CheckpointDiffQuery.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerNode, + layerCheckpointStore, + Layer.mock(ThreadManagement.ThreadManagementService)({ + getCheckpointContext: (id) => + projectionStore.getCheckpointContext(id).pipe(Effect.orDie), + }), + ), + ), + ), + ).pipe( + Layer.provide( + ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-capture-test-" }), + ), + Layer.provide(layerNode), + ); + + return yield* Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const vcsProcess = yield* VcsProcess.VcsProcess; + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const capture = yield* CheckpointCaptureService.CheckpointCaptureServiceV2; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: `${name}-` }); + const git = (cwd: string, ...args: ReadonlyArray) => + vcsProcess.run({ operation: "test.git", command: "git", cwd, args }).pipe( + Effect.map((result) => result.stdout.trim()), + Effect.orDie, + ); + const write = (file: string, contents: string) => + fileSystem + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe(Effect.andThen(fileSystem.writeFileString(file, contents)), Effect.orDie); + const initRepository = (cwd: string) => + Effect.gen(function* () { + yield* write(path.join(cwd, "README.md"), "# start\n"); + yield* git(cwd, "init"); + yield* git(cwd, "config", "user.email", "test@test.com"); + yield* git(cwd, "config", "user.name", "Test"); + yield* git(cwd, "add", "."); + yield* git(cwd, "commit", "-m", "initial commit"); + }); + const rootScope = { + id: repositoryRootScopeId, + threadId: repositoryThreadId, + runId: RunId.make(`run:${name}:1`), + nodeId: NodeId.make(`node:${name}:1`), + parentScopeId: null, + providerThreadId: repositoryProviderThreadId, + kind: "root_run" as const, + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: root, + createdAt: now, + }; + const event = { threadId: repositoryThreadId, providerInstanceId, occurredAt: now }; + yield* Effect.forEach( + [ + { + ...event, + id: EventId.make(`event:${name}:thread`), + type: "thread.created", + payload: { + createdBy: "user", + creationSource: "web", + id: repositoryThreadId, + projectId, + title: name, + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: repositoryThreadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }, + { + ...event, + id: EventId.make(`event:${name}:provider-thread`), + type: "provider-thread.updated", + driver, + payload: { + id: repositoryProviderThreadId, + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: repositoryThreadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }, + { + ...event, + id: EventId.make(`event:${name}:scope`), + type: "checkpoint-scope.created", + payload: rootScope, + }, + ] satisfies ReadonlyArray, + (seed) => projectionStore.apply(seed), + ); + const seedRun = (ordinal: number) => + Effect.forEach( + [ + { + ...event, + id: EventId.make(`event:${name}:run:${ordinal}`), + type: "run.updated", + runId: RunId.make(`run:${name}:${ordinal}`), + payload: { + id: RunId.make(`run:${name}:${ordinal}`), + threadId: repositoryThreadId, + ordinal, + providerInstanceId, + modelSelection, + providerThreadId: repositoryProviderThreadId, + userMessageId: MessageId.make(`message:${name}:${ordinal}`), + rootNodeId: NodeId.make(`node:${name}:${ordinal}`), + activeAttemptId: null, + status: "waiting", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }, + { + ...event, + id: EventId.make(`event:${name}:node:${ordinal}`), + type: "node.updated", + runId: RunId.make(`run:${name}:${ordinal}`), + payload: { + id: NodeId.make(`node:${name}:${ordinal}`), + threadId: repositoryThreadId, + runId: RunId.make(`run:${name}:${ordinal}`), + parentNodeId: null, + rootNodeId: NodeId.make(`node:${name}:${ordinal}`), + kind: "root_turn", + status: "waiting", + countsForRun: true, + providerThreadId: repositoryProviderThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: repositoryRootScopeId, + startedAt: now, + completedAt: null, + }, + }, + ] satisfies ReadonlyArray, + (seed) => projectionStore.apply(seed), + ); + const captureRun = (ordinal: number) => + capture + .execute({ + threadId: repositoryThreadId, + runId: RunId.make(`run:${name}:${ordinal}`), + scopeId: repositoryRootScopeId, + }) + .pipe(Effect.orDie); + const turn = (ordinal: number, edits: Effect.Effect) => + Effect.gen(function* () { + yield* seedRun(ordinal); + yield* checkpoints.captureBaseline({ + scope: rootScope, + ordinalWithinScope: ordinal - 1, + thread: { projectId, worktreePath: null }, + }); + yield* edits; + yield* captureRun(ordinal); + return (yield* Ref.get(committed)).flatMap((recorded) => { + if (recorded.type === "checkpoint-scope.created") { + labels.set(recorded.payload.id, recorded.payload.label ?? "unlabelled"); + return [{ type: "scope", label: recorded.payload.label ?? "unlabelled" }]; + } + if (recorded.type !== "checkpoint.captured") return []; + return [ + { + type: "checkpoint", + label: labels.get(recorded.payload.scopeId) ?? "unknown", + ordinal: recorded.payload.ordinalWithinScope, + run: recorded.payload.runId !== null, + status: recorded.payload.status, + files: recorded.payload.files.map((file) => file.path), + }, + ]; + }); + }).pipe(Effect.orDie); + return yield* use({ + root, + folders, + git, + initRepository, + write, + turn, + capture: captureRun, + commits, + threadId: repositoryThreadId, + ids: yield* IdAllocator.IdAllocatorV2, + diffs: yield* CheckpointDiffQuery.CheckpointDiffQuery, + }); + }).pipe(Effect.provide(layer), Effect.scoped); + }); + + it.effect("checkpoints the repositories a folder that is not a repository holds", () => + withTrackedRepositories("capture-wrapper", (thread) => + Effect.gen(function* () { + const { root } = thread; + const repository = (name: string) => ({ + name, + path: `${root}/${name}`, + isGitRepository: true, + }); + yield* Effect.forEach(["api", "web", "docs"], (name) => + thread.initRepository(`${root}/${name}`), + ); + yield* thread.write(`${root}/notes/todo.md`, "plain folder\n"); + yield* Ref.set(thread.folders, [ + repository("api"), + repository("web"), + { name: "notes", path: `${root}/notes`, isGitRepository: false }, + ]); + const ready = (label: string, ordinal: number, files?: ReadonlyArray) => ({ + type: "checkpoint", + label, + ordinal, + run: files !== undefined, + status: "ready", + files: files ?? [], + }); + const missingRoot = (ordinal: number, run: boolean) => ({ + ...ready("root", ordinal, run ? [] : undefined), + status: "missing", + }); + + // Only the repository the turn changed is recorded; `web` and the plain folder are not. + assert.deepEqual( + yield* thread.turn(1, thread.write(`${root}/api/README.md`, "# first\n")), + [ + { type: "scope", label: "api" }, + ready("api", 0), + ready("api", 1, ["README.md"]), + missingRoot(0, false), + missingRoot(1, true), + ], + ); + // An at-least-once retry of a settled run commits nothing more. + yield* thread.capture(1); + assert.strictEqual(yield* Ref.get(thread.commits), 1); + + // `docs` joins the project mid-thread and starts from this turn's baseline. `api` keeps + // the scope it had, and the checkpoint its first turn recorded is this turn's baseline. + yield* Ref.update(thread.folders, (current) => [...current, repository("docs")]); + assert.deepEqual( + yield* thread.turn( + 2, + // The agent commits its work in `api` and leaves `docs` uncommitted. + Effect.gen(function* () { + yield* thread.write(`${root}/api/src/main.ts`, "export {};\n"); + yield* thread.git(`${root}/api`, "add", "."); + yield* thread.git(`${root}/api`, "commit", "-m", "the turn's own commit"); + yield* thread.write(`${root}/docs/README.md`, "# docs\n"); + }), + ), + [ + ready("api", 2, ["src/main.ts"]), + { type: "scope", label: "docs" }, + ready("docs", 1), + ready("docs", 2, ["README.md"]), + missingRoot(0, false), + missingRoot(2, true), + ], + ); + const context = yield* ProjectionStore.ProjectionStoreV2.use((store) => + store.getCheckpointContext(thread.threadId), + ); + assert.sameMembers( + context.checkpointScopes.flatMap((scope) => + typeof scope.repositoryPath === "string" ? [scope.id] : [], + ), + yield* Effect.forEach(["api", "docs"], (name) => + thread.ids.allocate.checkpointScope({ + threadId: thread.threadId, + name: `repository:${root}/${name}`, + }), + ), + ); + + const lastTurn = yield* thread.diffs.getTurnDiff({ + threadId: thread.threadId, + fromTurnCount: 1, + toTurnCount: 2, + }); + assert.strictEqual(lastTurn.diff, ""); + assert.deepEqual( + lastTurn.repositories?.map(({ diff: _diff, ...repository }) => repository), + ["api", "docs"].map((name) => ({ + name, + repositoryPath: `${root}/${name}`, + relativePath: name, + })), + ); + assert.include(lastTurn.repositories?.[0]?.diff, "b/src/main.ts"); + assert.notInclude(lastTurn.repositories?.[0]?.diff, "README.md"); + // The whole thread: both of `api`'s turns, and `docs` from the turn it joined. + const wholeThread = yield* thread.diffs.getFullThreadDiff({ + threadId: thread.threadId, + toTurnCount: 2, + }); + assert.deepEqual( + wholeThread.repositories?.map((repository) => repository.name), + ["api", "docs"], + ); + assert.include(wholeThread.repositories?.[0]?.diff, "b/README.md"); + assert.include(wholeThread.repositories?.[0]?.diff, "b/src/main.ts"); + }), + ), + ); + + it.effect("keeps a clone inside a Git project folder out of that folder's checkpoint", () => + withTrackedRepositories("capture-nested", (thread) => + Effect.gen(function* () { + const { root } = thread; + const clone = `${root}/vendor/lib`; + yield* thread.initRepository(root); + yield* thread.initRepository(clone); + yield* Ref.set(thread.folders, [{ name: "lib", path: clone, isGitRepository: true }]); + + const recorded = yield* thread.turn( + 1, + Effect.all([ + thread.write(`${root}/README.md`, "# project\n"), + thread.write(`${clone}/README.md`, "# clone\n"), + ]), + ); + + // The project folder lists its own file, not the clone as a gitlink or an untracked tree. + assert.deepEqual( + recorded.flatMap((entry) => + entry.run === true ? [{ label: entry.label, files: entry.files }] : [], + ), + [ + { label: "lib", files: ["README.md"] }, + { label: "root", files: ["README.md"] }, + ], + ); + const turnDiff = yield* thread.diffs.getTurnDiff({ + threadId: thread.threadId, + fromTurnCount: 0, + toTurnCount: 1, + }); + assert.notInclude(turnDiff.diff, "vendor/lib"); + assert.deepEqual( + turnDiff.repositories?.map((repository) => repository.relativePath), + ["vendor/lib"], + ); + }), + ), + ); + + it.effect("keeps a submodule's pin in its repository's checkpoint", () => + withTrackedRepositories("capture-submodule", (thread) => + Effect.gen(function* () { + const { root } = thread; + const submodule = `${root}/vendor/lib`; + yield* thread.initRepository(root); + yield* thread.initRepository(submodule); + yield* thread.write( + `${root}/.gitmodules`, + '[submodule "lib"]\n\tpath = vendor/lib\n\turl = ../lib\n', + ); + yield* thread.git(root, "add", ".gitmodules", "vendor/lib"); + yield* thread.git(root, "commit", "-m", "Add lib"); + yield* Ref.set(thread.folders, [{ name: "lib", path: submodule, isGitRepository: true }]); + + const recorded = yield* thread.turn( + 1, + Effect.gen(function* () { + yield* thread.write(`${submodule}/README.md`, "# lib\n"); + yield* thread.git(submodule, "add", "README.md"); + yield* thread.git(submodule, "commit", "-m", "Describe lib"); + }), + ); + + assert.deepEqual( + recorded.flatMap((entry) => + entry.run === true ? [{ label: entry.label, files: entry.files }] : [], + ), + [ + { label: "lib", files: ["README.md"] }, + { label: "root", files: ["vendor/lib"] }, + ], + ); + }), + ), + ); }); diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 43cdae25d4bcd..119b5420be343 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -2,6 +2,7 @@ import { CheckpointScopeId, CommandId, type OrchestrationV2Checkpoint, + type OrchestrationV2CheckpointScope, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderThread, type OrchestrationV2Run, @@ -13,6 +14,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as CheckpointService from "./CheckpointService.ts"; @@ -20,6 +22,9 @@ import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; +// Git processes are already capped server-wide; this keeps one thread from taking every slot. +const REPOSITORY_CAPTURE_CONCURRENCY = 6; + export class CheckpointCaptureExecutionError extends Schema.TaggedError()( "CheckpointCaptureExecutionError", { @@ -65,8 +70,9 @@ export const layer: Layer.Layer< readonly runId: RunId; readonly scopeId: CheckpointScopeId; }) { + const context = yield* projections.getCheckpointCaptureContext(input.threadId, input); const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } = - yield* projections.getCheckpointCaptureContext(input.threadId, input); + context; // Stopped runs remain terminal; their checkpoint is the next message's rollback point. const stopped = run?.status === "interrupted" || run?.status === "cancelled"; @@ -113,23 +119,126 @@ export const layer: Layer.Layer< capturedAt: run.requestedAt, forceMissing: sideChat, }); - const threadStartCheckpoint = - baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0); - const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope) - ? null - : yield* materializeBaseline(baselineOrdinalWithinScope); - const checkpoint = yield* checkpoints.capture({ - scope, - runId: run.id, - nodeId: rootNode.id, - ordinalWithinScope: run.ordinal, - appRunOrdinal: run.ordinal, - capturedAt, - forceMissing: sideChat, + // The tracked Git folders the thread reaches now. One added since the turn began has no + // baseline, so its first checkpoint lists no files; one removed is simply not captured. + const repositoryScopes = + sideChat || context.thread === undefined + ? [] + : yield* checkpoints.repositoryScopes({ rootScope: scope, ...context.thread }); + const nested = + repositoryScopes.length === 0 + ? undefined + : yield* checkpoints.nestedScopePaths([scope, ...repositoryScopes]); + const excluded = (target: OrchestrationV2CheckpointScope) => { + const excludePaths = nested?.get(target.id); + return excludePaths === undefined ? {} : { excludePaths }; + }; + // Each scope is checked on its own, so a retried capture fills only what is missing. + const captureRoot = Effect.gen(function* () { + const threadStartCheckpoint = + baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0); + const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope) + ? null + : yield* materializeBaseline(baselineOrdinalWithinScope); + const checkpoint = yield* checkpoints.capture({ + scope, + runId: run.id, + nodeId: rootNode.id, + ordinalWithinScope: run.ordinal, + appRunOrdinal: run.ordinal, + capturedAt, + forceMissing: sideChat, + ...excluded(scope), + }); + return { threadStartCheckpoint, baselineCheckpoint, checkpoint }; + }); + const recordedScopes = new Map( + context.repositoryScopes.map((recorded) => [recorded.id, recorded]), + ); + const captureRepository = Effect.fnUntraced(function* ( + prepared: OrchestrationV2CheckpointScope, + ) { + const recorded = recordedScopes.get(prepared.id); + // A recorded scope keeps the run that first used it; only a renamed folder rewrites it. + const changed = + recorded === undefined || + recorded.cwd !== prepared.cwd || + recorded.label !== prepared.label; + const target = + recorded === undefined + ? prepared + : changed + ? { + ...prepared, + runId: recorded.runId, + nodeId: recorded.nodeId, + createdAt: recorded.createdAt, + } + : recorded; + const captured = yield* checkpoints.captureRepository({ + scope: target, + runId: run.id, + nodeId: rootNode.id, + ordinalWithinScope: run.ordinal, + capturedAt, + baselineCapturedAt: run.requestedAt, + baselineRecorded: context.repositoryScopesWithBaseline.includes(target.id), + ...excluded(target), + }); + // Only a repository with something to show is recorded, so the rest cost no events, + // rows or bytes on the wire. + return Option.match(captured, { + onNone: () => [], + onSome: (capture) => [{ scope: changed ? target : null, ...capture }], + }); }); + const [{ threadStartCheckpoint, baselineCheckpoint, checkpoint }, repositoryCaptures] = + yield* Effect.all( + [ + captureRoot, + Effect.forEach(repositoryScopes, captureRepository, { + concurrency: REPOSITORY_CAPTURE_CONCURRENCY, + }), + ], + { concurrency: 2 }, + ); // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run; const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`); + const checkpointEvent = (payload: OrchestrationV2Checkpoint) => + Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({ + id, + type: "checkpoint.captured" as const, + threadId: input.threadId, + ...(payload.runId === null ? {} : { runId: payload.runId }), + nodeId: payload.nodeId, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload, + })); + const repositoryEvents = yield* Effect.forEach(repositoryCaptures.flat(), (capture) => + Effect.gen(function* () { + return [ + ...(capture.scope === null + ? [] + : [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "checkpoint-scope.created" as const, + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: capture.scope, + }, + ]), + ...(capture.baseline === null ? [] : [yield* checkpointEvent(capture.baseline)]), + yield* checkpointEvent(capture.checkpoint), + ]; + }), + ); yield* eventSink.commitCommand({ commandId, threadId: input.threadId, @@ -137,6 +246,8 @@ export const layer: Layer.Layer< acceptedAt: capturedAt, effects: [], events: [ + // Root records come last: a client that takes the latest ordinal-0 baseline gets the thread's. + ...repositoryEvents.flat(), ...(threadStartCheckpoint === null ? [] : [ diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index 145de122f387a..360f7c84592e7 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -141,6 +141,7 @@ it.effect.each([ }), }), Layer.mock(CheckpointServiceV2)({ + discardRepositorySnapshots: () => Effect.void, restore: () => Effect.gen(function* () { calls.push("files"); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 224fafb02c92d..6fa62e14bc07d 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -98,7 +98,10 @@ it.effect.each(["initial", "waiting"])( Layer.provide( Layer.mergeAll( ThreadCommandExecutor.layer, - Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }), + Layer.mock(CheckpointService.CheckpointServiceV2)({ + restore, + discardRepositorySnapshots: () => Effect.void, + }), Layer.mock(EventSink.EventSinkV2)({}), IdAllocator.layer, Layer.mock(ProjectionStore.ProjectionStoreV2)({ @@ -259,6 +262,7 @@ it.effect.each([ }), }), Layer.mock(CheckpointService.CheckpointServiceV2)({ + discardRepositorySnapshots: () => Effect.void, restore: () => Effect.gen(function* () { assert.isTrue( @@ -452,6 +456,7 @@ it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( }), Layer.mock(GitWorkflow.GitWorkflowService)({}), Layer.mock(CheckpointService.CheckpointServiceV2)({ + discardRepositorySnapshots: () => Effect.void, restore: () => Deferred.succeed(restoreEntered, undefined).pipe( Effect.andThen(Deferred.await(releaseRestore)), @@ -535,6 +540,7 @@ const seedRollbackHistory = Effect.gen(function* () { const modelSelection = { instanceId: providerInstanceId, model: "test" }; const scopeId = CheckpointScopeId.make("rollback-history-root"); const otherScopeId = CheckpointScopeId.make("rollback-history-child"); + const repositoryScopeId = CheckpointScopeId.make("rollback-history-repository"); const runId = (ordinal: number) => RunId.make(`rollback-history-run-${ordinal}`); const nodeId = (ordinal: number) => NodeId.make(`rollback-history-node-${ordinal}`); const attemptId = (ordinal: number) => RunAttemptId.make(`rollback-history-attempt-${ordinal}`); @@ -735,9 +741,49 @@ const seedRollbackHistory = Effect.gen(function* () { }); } + // A tracked repository records only the turns that changed it: runs 2 and 4 here. + yield* apply({ + type: "checkpoint-scope.created", + payload: { + id: repositoryScopeId, + threadId, + runId: runId(2), + nodeId: nodeId(2), + parentScopeId: scopeId, + providerThreadId, + kind: "manual", + ordinalWithinParent: 1, + advancesAppRunCount: false, + cwd: process.cwd(), + label: "api", + repositoryPath: process.cwd(), + createdAt: now, + }, + }); + for (const ordinal of [2, 4]) { + yield* apply({ + type: "checkpoint.captured", + payload: { + id: CheckpointId.make(`rollback-history-repository-checkpoint-${ordinal}`), + threadId, + scopeId: repositoryScopeId, + runId: runId(ordinal), + nodeId: nodeId(ordinal), + parentCheckpointId: null, + ordinalWithinScope: ordinal, + appRunOrdinal: null, + ref: CheckpointRef.make(`refs/t3/rollback-history/repository/${ordinal}`), + status: "ready", + files: [], + capturedAt: now, + }, + }); + } + const rollbackCounts: number[] = []; const restored: CheckpointId[] = []; const deletedRefs: CheckpointId[] = []; + const discardedRepositoryOrdinals: number[] = []; const committed: OrchestrationV2DomainEvent[] = []; const serviceLayer = layerCheckpointRollbackService.pipe( Layer.provide( @@ -753,6 +799,10 @@ const seedRollbackHistory = Effect.gen(function* () { Effect.sync(() => { deletedRefs.push(...checkpoints.map((checkpoint) => checkpoint.id)); }), + discardRepositorySnapshots: ({ ordinals }) => + Effect.sync(() => { + discardedRepositoryOrdinals.push(...ordinals); + }), }), Layer.mock(EventSink.EventSinkV2)({ write: ({ events }) => @@ -806,6 +856,8 @@ const seedRollbackHistory = Effect.gen(function* () { rollbackCounts, restored, deletedRefs, + discardedRepositoryOrdinals, + repositoryScopeId, committed, }; }); @@ -866,11 +918,22 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe ); const checkpoints = yield* sql<{ status: string }>` SELECT status FROM orchestration_v2_projection_checkpoints - WHERE thread_id = ${threadId} ORDER BY ordinal_within_scope`; + WHERE thread_id = ${threadId} AND scope_id != ${history.repositoryScopeId} + ORDER BY ordinal_within_scope`; assert.deepEqual( checkpoints.map((checkpoint) => checkpoint.status), ["ready", "ready", "ready", "stale", "stale", "stale", "stale", "stale", "ready"], ); + // The repository keeps its state at the target and loses what the discarded runs recorded, + // including the snapshots that have no record. + const repositoryCheckpoints = yield* sql<{ status: string }>` + SELECT status FROM orchestration_v2_projection_checkpoints + WHERE scope_id = ${history.repositoryScopeId} ORDER BY ordinal_within_scope`; + assert.deepEqual( + repositoryCheckpoints.map((checkpoint) => checkpoint.status), + ["ready", "stale"], + ); + assert.deepEqual(history.discardedRepositoryOrdinals, [3, 4, 5, 6]); }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 8924a3eb9a78b..6332bededa052 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -155,6 +155,8 @@ export const layer: Layer.Layer< providerThread.providerSessionId === null || checkpoint === undefined || scope === undefined || + // A repository's checkpoints follow the thread's; they are not a place to rewind to. + typeof scope.repositoryPath === "string" || checkpoint.scopeId !== scope.id || // Missing snapshots support conversation rewind only. (checkpoint.status !== "ready" && @@ -341,9 +343,15 @@ export const layer: Layer.Layer< providerThreadTurns, }); if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint }); - if (staleCheckpoints.length > 0) { - yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints }); + const staleScopeCheckpoints = staleCheckpoints.filter((stale) => stale.scopeId === scope.id); + if (staleScopeCheckpoints.length > 0) { + yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleScopeCheckpoints }); } + yield* checkpoints.discardRepositorySnapshots({ + rootScope: scope, + thread: context.thread, + ordinals: runsToRollback.map((run) => run.ordinal), + }); // Lock against full-row thread writes that could restore the old native session after rollback. yield* threadCommands.withLock( diff --git a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts index 33a7490a0245a..c73e1be396187 100644 --- a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts @@ -1,4 +1,5 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -26,6 +27,7 @@ const layerProjection = Layer.mergeAll( SqlitePersistence.layerMemory, IdAllocator.layer, NodeCrypto.layer, + NodeServices.layer, ); it.effect("resolves the thread baseline after a second root run replaces scope ownership", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 62fa68c4c53af..5d6b88203b74d 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -1,8 +1,10 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { CheckpointScopeId, NodeId, + ProjectId, ProviderThreadId, RunId, ThreadId, @@ -16,12 +18,22 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as CheckpointService from "./CheckpointService.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; + +const layerNoTrackedFolders = Layer.merge( + NodeServices.layer, + Layer.mock(WorkspaceFolders.WorkspaceFolders)({ + forThread: () => Effect.succeed({ folders: [], extraRoots: [] }), + submodules: () => Effect.succeed([]), + }), +); it.effect( "skips unsupported baseline and turn checkpoints without swallowing capture failures", @@ -57,6 +69,7 @@ it.effect( Layer.provide( Layer.mergeAll( IdAllocator.layer, + layerNoTrackedFolders, Layer.mock(CheckpointStore.CheckpointStore)({ isGitRepository: () => Effect.succeed(true), hasCheckpointRef: () => Effect.succeed(false), @@ -126,6 +139,7 @@ it.effect( Layer.provide( Layer.mergeAll( IdAllocator.layer, + layerNoTrackedFolders, Layer.mock(CheckpointStore.CheckpointStore)({ isGitRepository: () => Effect.succeed(true), hasCheckpointRef: ({ checkpointRef }) => @@ -175,6 +189,147 @@ it.effect( }), ); +it.effect( + "asks Git about a tracked repository once a turn and snapshots it only when changed", + () => + Effect.gen(function* () { + const scope: OrchestrationV2CheckpointScope = { + id: CheckpointScopeId.make("checkpoint-scope:repositories"), + threadId: ThreadId.make("thread:repositories"), + runId: RunId.make("run:repositories:1"), + nodeId: NodeId.make("node:repositories:1"), + parentScopeId: null, + providerThreadId: ProviderThreadId.make("provider-thread:repositories"), + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/wrapper", + createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"), + }; + const thread = { projectId: ProjectId.make("project:repositories"), worktreePath: null }; + const repositories = Array.from({ length: 30 }, (_, index) => `/wrapper/repo-${index}`); + const [slowRepository, changedRepository] = [repositories[7]!, repositories[3]!]; + const startHead = "a".repeat(40); + const heads = yield* Ref.make>(new Map()); + const refs = yield* Ref.make>(new Set()); + const calls = yield* Ref.make>([]); + const record = (call: string) => Ref.update(calls, (current) => [...current, call]); + const slow = yield* Ref.make(true); + const slowStarted = yield* Deferred.make(); + const othersSeen = yield* Deferred.make(); + const layerTest = CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + NodeServices.layer, + Layer.mock(WorkspaceFolders.WorkspaceFolders)({ + forThread: () => + Effect.succeed({ + folders: [ + ...repositories.map((path) => ({ name: path, path, isGitRepository: true })), + { name: "notes", path: "/wrapper/notes", isGitRepository: false }, + ], + extraRoots: [], + }), + submodules: () => Effect.succeed([]), + }), + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: (cwd) => record(`probe ${cwd}`).pipe(Effect.as(cwd !== "/wrapper")), + resolveCleanHead: (cwd) => + Effect.gen(function* () { + // One repository is too slow for the turn to wait on. + if (cwd === slowRepository && (yield* Ref.get(slow))) { + yield* Deferred.succeed(slowStarted, undefined); + yield* Effect.sleep("1 minute"); + } + yield* record(`status ${cwd}`); + if ((yield* Ref.get(calls)).length === repositories.length - 1) { + yield* Deferred.succeed(othersSeen, undefined); + } + return (yield* Ref.get(heads)).get(cwd) ?? startHead; + }), + hasCheckpointRef: ({ checkpointRef }) => + Ref.get(refs).pipe(Effect.map((current) => current.has(checkpointRef))), + captureHeadCheckpoint: ({ cwd, head, checkpointRef }) => + record(`snapshot ${cwd} at ${head[0]}`).pipe( + Effect.andThen( + Ref.update(refs, (current) => new Set([...current, checkpointRef])), + ), + ), + diffCheckpoints: () => Effect.succeed("1\t0\tfile.ts\0"), + listAuthoredPaths: () => Effect.succeed(null), + }), + ), + ), + Layer.provideMerge(NodeCrypto.layer), + ); + + yield* Effect.gen(function* () { + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const scopes = yield* checkpoints.repositoryScopes({ rootScope: scope, ...thread }); + // The plain folder gets no scope. + assert.deepEqual( + scopes.map((repository) => repository.cwd), + repositories, + ); + const captureAll = (ordinalWithinScope: number) => + Effect.forEach(scopes, (repository) => + checkpoints.captureRepository({ + scope: repository, + runId: scope.runId!, + nodeId: scope.nodeId, + ordinalWithinScope, + capturedAt: scope.createdAt, + baselineCapturedAt: scope.createdAt, + baselineRecorded: false, + }), + ); + + // Every baseline shares the turn's budget; the slow repository is left without one. + const firstTurn = yield* checkpoints + .captureBaseline({ scope, ordinalWithinScope: 0, thread }) + .pipe(Effect.forkChild); + yield* Deferred.await(slowStarted); + yield* Deferred.await(othersSeen); + yield* TestClock.adjust("5 seconds"); + yield* Fiber.join(firstTurn); + yield* Ref.set(slow, false); + + // A turn that changes nothing writes nothing and records nothing. + assert.isTrue((yield* captureAll(1)).every(Option.isNone)); + assert.isFalse((yield* Ref.get(calls)).some((call) => call.startsWith("snapshot"))); + + // The next turn starts from what each repository's last run ended with, so only the + // thread's own folder is read. + yield* Ref.set(calls, []); + yield* checkpoints.captureBaseline({ scope, ordinalWithinScope: 1, thread }); + assert.deepEqual(yield* Ref.get(calls), ["probe /wrapper"]); + + // The turn commits in one repository: its baseline is snapshotted from where it started. + yield* Ref.set(heads, new Map([[changedRepository, "b".repeat(40)]])); + yield* Ref.set(calls, []); + const recorded = (yield* captureAll(2)).flatMap(Option.toArray); + assert.deepEqual( + recorded.map(({ baseline, checkpoint }) => ({ + cwd: scopes.find((repository) => repository.id === checkpoint.scopeId)?.cwd, + baseline: baseline?.ordinalWithinScope, + ordinal: checkpoint.ordinalWithinScope, + files: checkpoint.files.map((file) => file.path), + })), + [{ cwd: changedRepository, baseline: 1, ordinal: 2, files: ["file.ts"] }], + ); + assert.deepEqual( + (yield* Ref.get(calls)).filter((call) => call.startsWith("snapshot")), + [`snapshot ${changedRepository} at a`, `snapshot ${changedRepository} at b`], + ); + assert.lengthOf( + (yield* Ref.get(calls)).filter((call) => call.startsWith("status")), + repositories.length, + ); + }).pipe(Effect.provide(layerTest)); + }), +); + it.effect("records a repository probe failure as an error checkpoint, not a missing one", () => Effect.gen(function* () { const scope: OrchestrationV2CheckpointScope = { @@ -194,6 +349,7 @@ it.effect("records a repository probe failure as an error checkpoint, not a miss Layer.provide( Layer.mergeAll( IdAllocator.layer, + layerNoTrackedFolders, Layer.mock(CheckpointStore.CheckpointStore)({ isGitRepository: () => Effect.fail( diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 3e0fbe95e8aa4..129ced4225760 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -5,29 +5,39 @@ import { NodeId, OrchestrationV2Checkpoint, OrchestrationV2CheckpointScope, + type OrchestrationV2AppThread, + type ProjectId, ProviderThreadId, RunId, ThreadId, } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Hex from "effect/encoding/Hex"; +import * as FileSystem from "effect/FileSystem"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { isGitImport, parseTurnDiffFilesFromNumstat } from "../checkpointing/Diffs.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; const CHECKPOINT_REFS_PREFIX = "refs/t3/orchestration-v2/checkpoints"; const ROOT_CHECKPOINT_SCOPE_NAME = "root"; // The provider turn waits on the baseline, so a workspace too slow for this starts without one. // It bounds only the snapshot: waiting on the lock lets an in-flight capture finish the same ref. const BASELINE_CAPTURE_BUDGET = "5 seconds"; +// Git processes are already capped server-wide; this keeps one thread from taking every slot. +const REPOSITORY_SCOPE_CONCURRENCY = 6; export class CheckpointRootScopePrepareError extends Schema.TaggedError()( "CheckpointRootScopePrepareError", @@ -105,6 +115,54 @@ export type CheckpointServiceV2Error = typeof CheckpointServiceV2Error.Type; const isCheckpointRestoreError = Schema.is(CheckpointRestoreError); +/** Per scope, the other scopes' folders inside its own: relative, `/`-separated. */ +type NestedScopePaths = ReadonlyMap>; + +/** + * A scope leaves a folder that has its own scope to that scope, so a clone inside another checkout + * is not also recorded as that checkout's gitlink. A submodule stays: its gitlink is the commit + * its repository pins, which belongs to that repository's changes. Real paths, since a folder can + * be reached through a symlink. + */ +export const nestedScopePaths = Effect.fn("CheckpointService.nestedScopePaths")(function* ( + scopes: ReadonlyArray>, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const resolved = yield* Effect.forEach( + scopes, + (scope) => + fileSystem.realPath(scope.cwd).pipe( + Effect.orElseSucceed(() => path.resolve(scope.cwd)), + Effect.map((cwd) => ({ id: scope.id, cwd })), + ), + { concurrency: REPOSITORY_SCOPE_CONCURRENCY }, + ); + const nested = new Map>(); + for (const outer of resolved) { + const inside = resolved.flatMap((inner) => { + const relative = path.relative(outer.cwd, inner.cwd); + return relative === "" || + relative === ".." || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) + ? [] + : [relative.split(path.sep).join("/")]; + }); + if (inside.length === 0) continue; + const submodules = new Set( + WorkspaceFolders.parseGitmodulesPaths( + yield* fileSystem + .readFileString(path.join(outer.cwd, ".gitmodules")) + .pipe(Effect.orElseSucceed(() => "")), + ), + ); + const excluded = [...new Set(inside)].filter((relative) => !submodules.has(relative)); + if (excluded.length > 0) nested.set(outer.id, excluded); + } + return nested as NestedScopePaths; +}); + export interface CheckpointServiceV2Shape { readonly prepareRootRunScope: (input: { readonly threadId: ThreadId; @@ -114,9 +172,28 @@ export interface CheckpointServiceV2Shape { readonly cwd: string; readonly createdAt: DateTime.Utc; }) => Effect.Effect; + /** + * One scope per tracked Git folder the thread reaches now, under its root scope. Ids depend only + * on the thread and the tracked path, so every run names the same scope. Empty when the folders + * cannot be read: the thread then runs with its root scope alone. + */ + readonly repositoryScopes: (input: { + readonly rootScope: OrchestrationV2CheckpointScope; + readonly projectId: ProjectId; + readonly worktreePath: string | null; + }) => Effect.Effect>; + readonly nestedScopePaths: ( + scopes: ReadonlyArray>, + ) => Effect.Effect; readonly captureBaseline: (input: { readonly scope: OrchestrationV2CheckpointScope; readonly ordinalWithinScope: number; + /** + * Also baselines the tracked repositories this thread reaches, a few at a time and all within + * one budget, so many repositories delay a turn no longer than one. A repository that misses + * the budget has no baseline this turn. + */ + readonly thread?: Pick; }) => Effect.Effect; readonly materializeBaselineCheckpoint: (input: { readonly scope: OrchestrationV2CheckpointScope; @@ -135,7 +212,29 @@ export interface CheckpointServiceV2Shape { readonly appRunOrdinal: number | null; readonly capturedAt: DateTime.Utc; readonly forceMissing?: boolean; + readonly excludePaths?: ReadonlyArray; }) => Effect.Effect; + /** + * A tracked repository's checkpoint for a run, with the baseline before it unless that is + * already recorded. None when the run left the repository as it found it, which costs one + * status and writes nothing: a project can track dozens of repositories a turn never touches. + */ + readonly captureRepository: (input: { + readonly scope: OrchestrationV2CheckpointScope; + readonly runId: RunId; + readonly nodeId: NodeId; + readonly ordinalWithinScope: number; + readonly capturedAt: DateTime.Utc; + readonly baselineCapturedAt: DateTime.Utc; + readonly baselineRecorded: boolean; + readonly excludePaths?: ReadonlyArray; + }) => Effect.Effect< + Option.Option<{ + readonly baseline: OrchestrationV2Checkpoint | null; + readonly checkpoint: OrchestrationV2Checkpoint; + }>, + CheckpointServiceV2Error + >; readonly restore: (input: { readonly scope: OrchestrationV2CheckpointScope; readonly checkpoint: OrchestrationV2Checkpoint; @@ -144,6 +243,16 @@ export interface CheckpointServiceV2Shape { readonly scope: OrchestrationV2CheckpointScope; readonly checkpoints: ReadonlyArray; }) => Effect.Effect; + /** + * Drops the snapshots the thread's tracked repositories took at these run ordinals. A rollback + * reuses the ordinals, and a snapshot left behind would pass for a later turn's baseline. Most + * have no checkpoint record, so they are found by ordinal. A failure is logged, not raised. + */ + readonly discardRepositorySnapshots: (input: { + readonly rootScope: OrchestrationV2CheckpointScope; + readonly thread: Pick; + readonly ordinals: ReadonlyArray; + }) => Effect.Effect; } export class CheckpointServiceV2 extends Context.Service< @@ -237,11 +346,19 @@ function makeCheckpoint(input: { export const layer: Layer.Layer< CheckpointServiceV2, never, - CheckpointStore.CheckpointStore | Digest.Digest | IdAllocator.IdAllocatorV2 + | CheckpointStore.CheckpointStore + | Digest.Digest + | IdAllocator.IdAllocatorV2 + | WorkspaceFolders.WorkspaceFolders + | FileSystem.FileSystem + | Path.Path > = Layer.effect( CheckpointServiceV2, Effect.gen(function* () { const checkpointStore = yield* CheckpointStore.CheckpointStore; + const workspaceFolders = yield* WorkspaceFolders.WorkspaceFolders; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const crypto = yield* Digest.Digest; const checkpointRefFor = (input: Parameters[0]) => checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Digest.Digest, crypto)); @@ -264,7 +381,31 @@ export const layer: Layer.Layer< ), ); - const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) => + // What this process knows of each repository scope's folder as of a run ordinal. With + // `cleanHead` the folder matched that commit exactly, and no snapshot ref need exist until a + // turn changes it; null means the ordinal's ref holds its state. Unknown after a restart. + const repositoryStates = new Map< + CheckpointScopeId, + { + readonly ordinal: number; + readonly cleanHead: string | null; + /** Epoch seconds. */ + readonly seenAt: number; + } + >(); + const noteRepositoryState = Effect.fnUntraced(function* ( + scopeId: CheckpointScopeId, + state: { readonly ordinal: number; readonly cleanHead: string | null }, + ) { + const seenAt = Math.floor((yield* Clock.currentTimeMillis) / 1000); + repositoryStates.set(scopeId, { ...state, seenAt }); + }); + + const captureScopeBaseline = (input: { + readonly scope: OrchestrationV2CheckpointScope; + readonly ordinalWithinScope: number; + readonly excludePaths: ReadonlyArray | undefined; + }) => withWorkspaceLock( input.scope.cwd, Effect.gen(function* () { @@ -288,6 +429,7 @@ export const layer: Layer.Layer< .captureCheckpoint({ cwd: input.scope.cwd, checkpointRef, + ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), }) .pipe( Effect.timeout(BASELINE_CAPTURE_BUDGET), @@ -307,6 +449,37 @@ export const layer: Layer.Layer< ), ); + // A clean repository is only noted, which costs one status. One with uncommitted work is + // snapshotted now, before the turn can change it. + const noteRepositoryBaseline = (input: { + readonly scope: OrchestrationV2CheckpointScope; + readonly ordinalWithinScope: number; + readonly excludePaths: ReadonlyArray | undefined; + }) => + withWorkspaceLock( + input.scope.cwd, + Effect.gen(function* () { + const { cwd, id } = input.scope; + // Usually the state its last run ended with, so most turns start without asking Git. + if (repositoryStates.get(id)?.ordinal === input.ordinalWithinScope) return; + const cleanHead = yield* checkpointStore.resolveCleanHead(cwd); + if (cleanHead === null) { + const checkpointRef = yield* checkpointRefFor({ + scopeId: id, + ordinalWithinScope: input.ordinalWithinScope, + }); + if (!(yield* checkpointStore.hasCheckpointRef({ cwd, checkpointRef }))) { + yield* checkpointStore.captureCheckpoint({ + cwd, + checkpointRef, + ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), + }); + } + } + yield* noteRepositoryState(id, { ordinal: input.ordinalWithinScope, cleanHead }); + }), + ); + const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] = (input) => withWorkspaceLock( @@ -364,7 +537,12 @@ export const layer: Layer.Layer< ), ); - const capture: CheckpointServiceV2Shape["capture"] = (input) => + const capture = ( + input: Parameters[0] & { + /** The commit a clean folder matches, which then needs no staging to snapshot. */ + readonly cleanHead?: string; + }, + ) => withWorkspaceLock( input.scope.cwd, Effect.gen(function* () { @@ -406,25 +584,32 @@ export const layer: Layer.Layer< }); } - const captureStatus = yield* checkpointStore - .captureCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), - }) - .pipe( - Effect.as("ready" as const), - Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), - }), - Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint capture failed", { - scopeId: input.scope.id, + const captureStatus = yield* ( + input.cleanHead === undefined + ? checkpointStore.captureCheckpoint({ + cwd: input.scope.cwd, checkpointRef, - cause: String(cause), - }).pipe(Effect.as("error" as const)), - ), - ); + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), + ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), + }) + : checkpointStore.captureHeadCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + head: input.cleanHead, + }) + ).pipe( + Effect.as("ready" as const), + Effect.catchTags({ + VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), + }), + Effect.catch((cause) => + Effect.logWarning("orchestration V2 checkpoint capture failed", { + scopeId: input.scope.id, + checkpointRef, + cause: String(cause), + }).pipe(Effect.as("error" as const)), + ), + ); if (captureStatus !== "ready") { return makeCheckpoint({ @@ -469,6 +654,8 @@ export const layer: Layer.Layer< fallbackFromToHead: false, ignoreWhitespace: false, format: "numstat", + // An earlier checkpoint can predate a nested folder getting its own scope. + ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), }), checkpointStore.listAuthoredPaths(refs).pipe( Effect.catch((cause) => @@ -561,6 +748,229 @@ export const layer: Layer.Layer< ), ); + const resolveNestedScopePaths: CheckpointServiceV2Shape["nestedScopePaths"] = (scopes) => + nestedScopePaths(scopes).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); + + const repositoryScopes: CheckpointServiceV2Shape["repositoryScopes"] = Effect.fn( + "CheckpointService.repositoryScopes", + )( + function* (input) { + const [workspace, submodules] = yield* Effect.all([ + workspaceFolders.forThread(input), + workspaceFolders.submodules(input), + ]); + return yield* Effect.forEach( + [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules], + (folder) => + idAllocator.allocate + .checkpointScope({ + threadId: input.rootScope.threadId, + name: `repository:${folder.repositoryPath ?? folder.path}`, + }) + .pipe( + Effect.map( + (id) => + ({ + id, + threadId: input.rootScope.threadId, + runId: input.rootScope.runId, + nodeId: input.rootScope.nodeId, + parentScopeId: input.rootScope.id, + providerThreadId: input.rootScope.providerThreadId, + kind: "manual", + ordinalWithinParent: 1, + advancesAppRunCount: false, + cwd: folder.path, + label: folder.name, + repositoryPath: folder.repositoryPath ?? folder.path, + createdAt: input.rootScope.createdAt, + }) satisfies OrchestrationV2CheckpointScope, + ), + ), + ); + }, + (effect, input) => + effect.pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration V2 repository checkpoint scopes unavailable", { + threadId: input.rootScope.threadId, + cause, + }).pipe(Effect.as([])), + ), + ), + ); + + const captureRepositoryBaselines = Effect.fn("CheckpointService.captureRepositoryBaselines")( + function* (input: { + readonly scopes: ReadonlyArray; + readonly ordinalWithinScope: number; + readonly nested: NestedScopePaths; + }) { + const captured = yield* Effect.forEach( + input.scopes, + (scope) => + noteRepositoryBaseline({ + scope, + ordinalWithinScope: input.ordinalWithinScope, + excludePaths: input.nested.get(scope.id), + }).pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration V2 repository baseline capture failed", { + scopeId: scope.id, + cause, + }), + ), + ), + { concurrency: REPOSITORY_SCOPE_CONCURRENCY, discard: true }, + ).pipe(Effect.timeoutOption(BASELINE_CAPTURE_BUDGET)); + if (Option.isNone(captured)) { + yield* Effect.logWarning( + "orchestration V2 repository baselines ran out of time; the rest start without one", + { scopeCount: input.scopes.length }, + ); + } + }, + ); + + const captureRepository: CheckpointServiceV2Shape["captureRepository"] = Effect.fn( + "CheckpointService.captureRepository", + )(function* (input) { + const { cwd, id } = input.scope; + const baselineOrdinal = input.ordinalWithinScope - 1; + const start = yield* withWorkspaceLock( + cwd, + Effect.gen(function* () { + const cleanHead = yield* checkpointStore + .resolveCleanHead(cwd) + .pipe(Effect.orElseSucceed(() => null)); + const stored = repositoryStates.get(id); + const known = stored?.ordinal === baselineOrdinal ? stored : undefined; + const cleanAtStart = known?.cleanHead ?? null; + const unchanged = { changed: false as const, cleanHead }; + if (cleanHead !== null && cleanAtStart === cleanHead) return unchanged; + const baselineRef = yield* checkpointRefFor({ + scopeId: id, + ordinalWithinScope: baselineOrdinal, + }); + const baselineExists = yield* checkpointStore + .hasCheckpointRef({ cwd, checkpointRef: baselineRef }) + .pipe(Effect.orElseSucceed(() => false)); + if (!baselineExists) { + // The turn started on a clean folder; its snapshot was left until one was needed. + if (known !== undefined && cleanAtStart !== null) { + yield* checkpointStore + .captureHeadCheckpoint({ + cwd, + checkpointRef: baselineRef, + head: cleanAtStart, + seenAt: known.seenAt, + }) + .pipe(Effect.ignore); + } else if (cleanHead !== null) { + // How the turn started is unknown and nothing is uncommitted: nothing to show. + return unchanged; + } + } + return { changed: true as const, cleanHead }; + }), + ); + const settled = { ordinal: input.ordinalWithinScope, cleanHead: start.cleanHead }; + if (!start.changed) { + yield* noteRepositoryState(id, settled); + return Option.none(); + } + const baseline = input.baselineRecorded + ? null + : yield* materializeBaselineCheckpoint({ + scope: input.scope, + ordinalWithinScope: baselineOrdinal, + nodeId: input.nodeId, + capturedAt: input.baselineCapturedAt, + }); + const checkpoint = yield* capture({ + scope: input.scope, + runId: input.runId, + nodeId: input.nodeId, + ordinalWithinScope: input.ordinalWithinScope, + appRunOrdinal: null, + capturedAt: input.capturedAt, + ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), + ...(start.cleanHead === null ? {} : { cleanHead: start.cleanHead }), + }); + if (checkpoint.status !== "ready") { + repositoryStates.delete(id); + return Option.some({ baseline, checkpoint }); + } + yield* noteRepositoryState(id, settled); + // A pull or a commit of what was already there moves the snapshot and lists no file. + return checkpoint.files.length === 0 && (baseline === null || baseline.status === "ready") + ? Option.none() + : Option.some({ baseline, checkpoint }); + }); + + const discardRepositorySnapshots: CheckpointServiceV2Shape["discardRepositorySnapshots"] = + Effect.fn("CheckpointService.discardRepositorySnapshots")(function* (input) { + if (input.ordinals.length === 0) return; + const repositories = yield* repositoryScopes({ + rootScope: input.rootScope, + ...input.thread, + }); + yield* Effect.forEach( + repositories, + (scope) => + withWorkspaceLock( + scope.cwd, + Effect.gen(function* () { + repositoryStates.delete(scope.id); + yield* checkpointStore.deleteCheckpointRefs({ + cwd: scope.cwd, + checkpointRefs: yield* Effect.forEach(input.ordinals, (ordinalWithinScope) => + checkpointRefFor({ scopeId: scope.id, ordinalWithinScope }), + ), + }); + }), + ).pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration V2 stale repository snapshots kept", { + scopeId: scope.id, + cause: String(cause), + }), + ), + ), + { concurrency: REPOSITORY_SCOPE_CONCURRENCY, discard: true }, + ); + }); + + const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = Effect.fn( + "CheckpointService.captureBaseline", + )(function* (input) { + const repositories = + input.thread === undefined + ? [] + : yield* repositoryScopes({ rootScope: input.scope, ...input.thread }); + if (repositories.length === 0) { + return yield* captureScopeBaseline({ ...input, excludePaths: undefined }); + } + const nested = yield* resolveNestedScopePaths([input.scope, ...repositories]); + // Side by side, so the repositories add no wait of their own; the thread folder's failure + // is still the caller's to report once they have had their turn. + const [root] = yield* Effect.all( + [ + Effect.exit(captureScopeBaseline({ ...input, excludePaths: nested.get(input.scope.id) })), + captureRepositoryBaselines({ + scopes: repositories, + ordinalWithinScope: input.ordinalWithinScope, + nested, + }), + ], + { concurrency: 2 }, + ); + if (Exit.isFailure(root)) return yield* Effect.failCause(root.cause); + }); + const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) => withWorkspaceLock( input.scope.cwd, @@ -591,11 +1001,15 @@ export const layer: Layer.Layer< }), ), ), + repositoryScopes, + nestedScopePaths: resolveNestedScopePaths, captureBaseline, materializeBaselineCheckpoint, capture, + captureRepository, restore, deleteStaleRefs, + discardRepositorySnapshots, } satisfies CheckpointServiceV2Shape); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c732e0ca67ccf..97db6e6b5951a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -13664,6 +13664,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Checkpoint ${command.checkpointId} belongs to scope ${targetScope.id}, not ${command.scopeId}.`, }); } + // A repository's checkpoints follow the thread's; they are not a place to rewind to. + if (typeof targetScope.repositoryPath === "string") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Checkpoint ${command.checkpointId} belongs to a tracked repository; roll back to the thread's own checkpoint instead.`, + }); + } if (command.restoreFiles !== false) { const isolated = yield* isCheckpointRestoreIsolated(projection.thread, targetScope, { projects, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 8b967f648165f..961dee0e49db1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -3841,6 +3841,52 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { }, }); + // A tracked repository's scope names the run that first changed it, here one outside the + // window, while its newest checkpoint belongs to a run inside it. + const repositoryScope = { + id: CheckpointScopeId.make("scope:bounded-sql-history:repository"), + threadId, + runId: RunId.make("run:bounded-sql-history:1"), + nodeId: NodeId.make("node:bounded-sql-history:1"), + parentScopeId: scopeId, + providerThreadId: null, + kind: "manual" as const, + ordinalWithinParent: 1, + advancesAppRunCount: false, + cwd: "/repo/worktree/api", + label: "api", + repositoryPath: "/repo/worktree/api", + createdAt: now, + }; + const repositoryCheckpointId = CheckpointId.make("checkpoint:bounded-sql-history:repository"); + yield* projectionStore.apply({ + id: EventId.make("event:bounded-sql-history:repository-scope"), + type: "checkpoint-scope.created", + threadId, + occurredAt: now, + payload: repositoryScope, + }); + yield* projectionStore.apply({ + id: EventId.make("event:bounded-sql-history:repository-checkpoint"), + type: "checkpoint.captured", + threadId, + occurredAt: now, + payload: { + id: repositoryCheckpointId, + threadId, + scopeId: repositoryScope.id, + runId: RunId.make("run:bounded-sql-history:1000"), + nodeId: NodeId.make("node:bounded-sql-history:1000"), + parentCheckpointId: null, + ordinalWithinScope: 1_000, + appRunOrdinal: null, + ref: CheckpointRef.make("refs/t3/bounded-sql-history/repository/1000"), + status: "ready", + files: [{ path: "src/main.ts", kind: "modified", additions: 1, deletions: 0 }], + capturedAt: now, + }, + }); + const snapshots = yield* Effect.all( Array.from({ length: 4 }, () => projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 }), @@ -3859,11 +3905,12 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ); assert.deepEqual( snapshot.projection.checkpointScopes.map((scope) => scope.id), - [scopeId], + [scopeId, repositoryScope.id], ); + assert.deepEqual(snapshot.projection.checkpointScopes[1], repositoryScope); assert.deepEqual( snapshot.projection.checkpoints.map((checkpoint) => checkpoint.id), - [baselineId], + [repositoryCheckpointId, baselineId], ); } const humanWindow = () => diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 3bdbbffc0373c..cffd1b5932856 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -243,6 +243,9 @@ const ProjectionCheckpointContext = Schema.Struct({ runId, kind, cwd, + // SQLite reads an absent JSON key as null. + label: Schema.optionalKey(Schema.NullOr(Schema.String)), + repositoryPath: Schema.optionalKey(Schema.NullOr(Schema.String)), })), ), checkpoints: Schema.Array( @@ -273,6 +276,12 @@ export interface ProjectionCheckpointCaptureContext { readonly preservedCheckpointOrdinals: ReadonlyArray; /** Side chats share their parent's worktree and never snapshot it. */ readonly sideChat: boolean; + /** What resolves the tracked folders the thread reaches. */ + readonly thread: Pick | undefined; + /** Every repository scope the thread has recorded so far. */ + readonly repositoryScopes: ReadonlyArray; + /** Repository scopes whose baseline for this run a runless baseline must not overwrite. */ + readonly repositoryScopesWithBaseline: ReadonlyArray; } const RollbackTargetAttempts = Schema.Array( @@ -294,6 +303,7 @@ export interface ProjectionCheckpointRollbackContext { readonly rolledBackAttemptIds: ReadonlyArray; readonly runsToRollback: ReadonlyArray; readonly rootNodes: ReadonlyArray; + /** Ready checkpoints of the target scope and of repository scopes that the rollback discards. */ readonly staleCheckpoints: ReadonlyArray; } @@ -4196,7 +4206,10 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_checkpoint_scopes WHERE thread_id = ${threadId} AND (run_id IN (SELECT value FROM json_each(${cohortRunIds})) - OR node_id IN (SELECT value FROM json_each(${cohortNodeIds}))) + OR node_id IN (SELECT value FROM json_each(${cohortNodeIds})) + -- A repository scope names the run that first used it; every later run's + -- checkpoints still need its label. + OR kind = 'manual') ORDER BY ordinal_within_parent ASC, scope_id ASC `, fields !== undefined && !fields.includes("checkpoints") @@ -5878,7 +5891,9 @@ export const layer: Layer.Layer = `, sql` SELECT scope_id AS id, run_id AS "runId", kind, - json_extract(payload_json, '$.cwd') AS cwd + json_extract(payload_json, '$.cwd') AS cwd, + json_extract(payload_json, '$.label') AS label, + json_extract(payload_json, '$.repositoryPath') AS "repositoryPath" FROM orchestration_v2_projection_checkpoint_scopes WHERE thread_id = ${threadId} ORDER BY ordinal_within_parent ASC, scope_id ASC @@ -5911,8 +5926,14 @@ export const layer: Layer.Layer = sql .withTransaction( Effect.gen(function* () { - const threadRows = yield* sql<{ readonly side_chat: number | null }>` - SELECT json_extract(payload_json, '$.lineage.sideChat') AS side_chat + const threadRows = yield* sql<{ + readonly side_chat: number | null; + readonly project_id: ProjectId; + readonly worktree_path: string | null; + }>` + SELECT json_extract(payload_json, '$.lineage.sideChat') AS side_chat, + json_extract(payload_json, '$.projectId') AS project_id, + json_extract(payload_json, '$.worktreePath') AS worktree_path FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId} LIMIT 1`; if (threadRows[0] === undefined) { return yield* new ProjectionStoreThreadNotFoundError({ threadId }); @@ -5924,7 +5945,15 @@ export const layer: Layer.Layer = runRows[0] === undefined ? undefined : yield* decodeRunPayload(runRows[0].payload_json); - const [nodeRows, scopeRows, providerRows, preservedRows] = yield* Effect.all([ + const preservedCheckpoint = sql`(status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`; + const [ + nodeRows, + scopeRows, + providerRows, + preservedRows, + repositoryScopeRows, + repositoryBaselineRows, + ] = yield* Effect.all([ sql`SELECT payload_json FROM orchestration_v2_projection_nodes WHERE thread_id = ${threadId} AND node_id = ${run?.rootNodeId ?? null}`, sql`SELECT payload_json FROM orchestration_v2_projection_checkpoint_scopes @@ -5937,7 +5966,16 @@ export const layer: Layer.Layer = sql<{ readonly ordinal: number }>`SELECT ordinal_within_scope AS ordinal FROM orchestration_v2_projection_checkpoints WHERE thread_id = ${threadId} AND scope_id = ${target.scopeId} - AND (status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`, + AND ${preservedCheckpoint}`, + sql`SELECT payload_json FROM orchestration_v2_projection_checkpoint_scopes + WHERE thread_id = ${threadId} AND kind = 'manual' ORDER BY scope_id ASC`, + sql<{ readonly scope_id: CheckpointScopeId }>`SELECT scope_id + FROM orchestration_v2_projection_checkpoints + WHERE thread_id = ${threadId} + AND ordinal_within_scope = ${Math.max(0, (run?.ordinal ?? 0) - 1)} + AND scope_id IN (SELECT scope_id FROM orchestration_v2_projection_checkpoint_scopes + WHERE thread_id = ${threadId} AND kind = 'manual') + AND ${preservedCheckpoint}`, ]); return { run, @@ -5955,6 +5993,15 @@ export const layer: Layer.Layer = : yield* decodeProviderThreadPayload(providerRows[0].payload_json), preservedCheckpointOrdinals: preservedRows.map(({ ordinal }) => ordinal), sideChat: threadRows[0].side_chat === 1, + thread: { + projectId: threadRows[0].project_id, + worktreePath: threadRows[0].worktree_path, + }, + repositoryScopes: yield* decodeRows( + decodeCheckpointScopePayload, + threadId, + )(repositoryScopeRows), + repositoryScopesWithBaseline: repositoryBaselineRows.map((row) => row.scope_id), }; }), ) @@ -6041,9 +6088,13 @@ export const layer: Layer.Layer = WHERE run.thread_id = ${threadId} AND run.status = 'rolled_back' AND attempt.thread_id = ${threadId}`, sql`SELECT payload_json FROM orchestration_v2_projection_checkpoints - WHERE thread_id = ${threadId} AND scope_id = ${scope.id} AND status = 'ready' - AND app_run_ordinal > ${targetOrdinal} - ORDER BY ordinal_within_scope ASC`, + WHERE thread_id = ${threadId} AND status = 'ready' + AND ((scope_id = ${scope.id} AND app_run_ordinal > ${targetOrdinal}) + -- Repository checkpoints carry no app run ordinal; theirs is the run's ordinal. + OR (ordinal_within_scope > ${targetOrdinal} AND scope_id IN ( + SELECT scope_id FROM orchestration_v2_projection_checkpoint_scopes + WHERE thread_id = ${threadId} AND kind = 'manual'))) + ORDER BY scope_id = ${scope.id} DESC, scope_id ASC, ordinal_within_scope ASC`, ]); const targetAttempt = (yield* decodeRollbackTargetAttempts(attemptRows))[0]; const runsToRollback = yield* decodeRows(decodeRunPayload, threadId)(runRows); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 0e8898cf0623b..f9d8f136f8d74 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -1405,6 +1405,7 @@ it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as co }), Layer.succeed(RunFinalizationService.RunFinalizationObserver, { refresh: () => Effect.void, + refreshRepositories: () => Effect.void, refreshAfterTurn: () => Ref.update(refreshes, (count) => count + 1), }), ), @@ -3626,6 +3627,7 @@ function captureRootRunTermination(input: { ServerSettings.layerTest(), Layer.succeed(RunFinalizationService.RunFinalizationObserver, { refresh: () => Effect.void, + refreshRepositories: () => Effect.void, refreshAfterTurn: () => Ref.update(observed, (current) => [...current, "pull-requests-refreshed"]).pipe( Effect.andThen(input.refreshAfterTurn ?? Effect.void), diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 10f10a98de0a4..129a07e2f5094 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -939,6 +939,7 @@ export const layer: Layer.Layer< .captureBaseline({ scope: input.checkpointScope, ordinalWithinScope: Math.max(0, input.run.ordinal - 1), + thread: input.appThread, }) .pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts index 9234add511d23..313fc98c51990 100644 --- a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts +++ b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + CheckpointRef, CheckpointScopeId, ProjectId, RunId, @@ -40,6 +41,16 @@ it.effect("completes finalization when the post-checkpoint workspace refresh fai const threadId = ThreadId.make("thread_refresh_failure"); const runId = RunId.make("run_refresh_failure"); const scopeId = CheckpointScopeId.make("scope_refresh_failure"); + const usedRepositoryScopeId = CheckpointScopeId.make("scope_refresh_failure_api"); + const idleRepositoryScopeId = CheckpointScopeId.make("scope_refresh_failure_docs"); + const repositoryCheckpoint = (repositoryScopeId: CheckpointScopeId, checkpointRunId: RunId) => ({ + scopeId: repositoryScopeId, + runId: checkpointRunId, + ordinalWithinScope: 1, + appRunOrdinal: null, + status: "ready" as const, + ref: CheckpointRef.make(`refs/t3/test/${repositoryScopeId}`), + }); const captured: string[] = []; const layer = RunFinalization.layer.pipe( Layer.provide( @@ -54,8 +65,27 @@ it.effect("completes finalization when the post-checkpoint workspace refresh fai getCheckpointContext: () => Effect.succeed({ runs: [], - checkpointScopes: [{ id: scopeId, runId, kind: "root_run" as const, cwd: "/repo" }], - checkpoints: [], + checkpointScopes: [ + { id: scopeId, runId, kind: "root_run" as const, cwd: "/repo" }, + { + id: usedRepositoryScopeId, + runId, + kind: "manual" as const, + cwd: "/api", + repositoryPath: "/api", + }, + { + id: idleRepositoryScopeId, + runId, + kind: "manual" as const, + cwd: "/docs", + repositoryPath: "/docs", + }, + ], + checkpoints: [ + repositoryCheckpoint(usedRepositoryScopeId, runId), + repositoryCheckpoint(idleRepositoryScopeId, RunId.make("run_before")), + ], }), }), Layer.succeed(RunFinalization.RunFinalizationObserver, { @@ -68,6 +98,10 @@ it.effect("completes finalization when the post-checkpoint workspace refresh fai }); }), refreshAfterTurn: () => Effect.void, + refreshRepositories: ({ cwds }) => + Effect.sync(() => { + captured.push(`repositories:${cwds.join(",")}`); + }), }), ), ), @@ -75,7 +109,8 @@ it.effect("completes finalization when the post-checkpoint workspace refresh fai return Effect.gen(function* () { const service = yield* RunFinalization.RunFinalizationService; yield* service.finalize({ threadId, runId, scopeId }); - assert.deepEqual(captured, ["checkpoint", "refresh"]); + // Only the tracked repository this run checkpointed is refreshed. + assert.deepEqual(captured, ["checkpoint", "refresh", "repositories:/api"]); }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.ts b/apps/server/src/orchestration-v2/RunFinalizationService.ts index 6da6833ac7936..55d0707d1c6f4 100644 --- a/apps/server/src/orchestration-v2/RunFinalizationService.ts +++ b/apps/server/src/orchestration-v2/RunFinalizationService.ts @@ -14,6 +14,8 @@ import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts"; import * as CheckpointCapture from "./CheckpointCaptureService.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +const REPOSITORY_REFRESH_CONCURRENCY = 4; + export class RunFinalizationError extends Schema.TaggedError()( "RunFinalizationError", { @@ -37,8 +39,17 @@ export class RunFinalizationObserver extends Context.Reference<{ readonly threadId: ThreadId; readonly runId: RunId; }) => Effect.Effect; + /** Local status of the tracked repositories a run checkpointed. Returns before it finishes. */ + readonly refreshRepositories: (input: { + readonly threadId: ThreadId; + readonly cwds: ReadonlyArray; + }) => Effect.Effect; }>("t3/orchestration-v2/RunFinalizationObserver", { - defaultValue: () => ({ refresh: () => Effect.void, refreshAfterTurn: () => Effect.void }), + defaultValue: () => ({ + refresh: () => Effect.void, + refreshAfterTurn: () => Effect.void, + refreshRepositories: () => Effect.void, + }), }) {} export class RunFinalizationService extends Context.Service< @@ -87,6 +98,17 @@ const make = Effect.gen(function* () { }), ); } + const repositoryScopeIds = new Set( + projection.checkpoints.flatMap((checkpoint) => + checkpoint.runId === input.runId ? [checkpoint.scopeId] : [], + ), + ); + const cwds = projection.checkpointScopes.flatMap((scope) => + typeof scope.repositoryPath === "string" && repositoryScopeIds.has(scope.id) + ? [scope.cwd] + : [], + ); + if (cwds.length > 0) yield* observer.refreshRepositories({ threadId: input.threadId, cwds }); }); return RunFinalizationService.of({ finalize }); }); @@ -103,6 +125,7 @@ export const layerObserver = Layer.effect( const projects = yield* ProjectService.ProjectService; const enrichment = yield* ProjectEnrichment.ProjectEnrichmentService; const pullRequestLookups = yield* FiberMap.make(); + const repositoryRefreshes = yield* FiberMap.make(); const identityRefreshes = yield* FiberMap.make(); // A turn can add the first remote (`git remote add`, `gh repo create --push`), which the // enrichment and resolver caches would otherwise keep reporting as missing for a minute. @@ -128,6 +151,27 @@ export const layerObserver = Layer.effect( ); return { refreshAfterTurn: pullRequests.refreshAfterTurn, + // A project can track dozens of repositories, so the next turn must not wait for them all. + // A newer turn's refresh replaces a running one. + refreshRepositories: Effect.fn("RunFinalizationService.refreshRepositories")(function* ({ + threadId, + cwds, + }) { + yield* Effect.forEach( + cwds, + (cwd) => + vcsStatus.refreshLocalStatus(cwd).pipe( + Effect.catch((error) => + Effect.logWarning("failed to refresh repository status after run completion", { + threadId, + cwd, + detail: error.message, + }), + ), + ), + { concurrency: REPOSITORY_REFRESH_CONCURRENCY, discard: true }, + ).pipe(FiberMap.run(repositoryRefreshes, threadId)); + }), refresh: Effect.fn("RunFinalizationService.refresh")( function* ({ cwd, threadId, runId }) { const [, local] = yield* Effect.all( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 9948b0c8e1fbb..5ec133e3db453 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -66,8 +66,12 @@ export const layerEventInfrastructure = Layer.mergeAll( OrchestrationCommandReceipts.layer, ); +const layerWorkspaceFoldersProvided = WorkspaceFolders.layer.pipe( + Layer.provide(ProjectStore.layer), +); + const layerRuntimePolicyProvided = RuntimePolicy.layerFromProjectStore.pipe( - Layer.provide(WorkspaceFolders.layer), + Layer.provide(layerWorkspaceFoldersProvided), Layer.provide(ProjectStore.layer), ); @@ -121,7 +125,7 @@ const layerProviderEventIngestorProvided = ProviderEventIngestor.layer.pipe( ); const layerCheckpointServiceProvided = CheckpointService.layer.pipe( - Layer.provide(IdAllocator.layer), + Layer.provide(Layer.merge(IdAllocator.layer, layerWorkspaceFoldersProvided)), ); const layerContextHandoffServiceProvided = ContextHandoffService.layer.pipe( Layer.provide(IdAllocator.layer), diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 9f035b7e039b7..49966a4aa644f 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -62,6 +62,7 @@ import * as RunExecutionService from "../RunExecutionService.ts"; import * as RunFinalizationService from "../RunFinalizationService.ts"; import * as ThreadTitleRegenerationService from "../ThreadTitleRegenerationService.ts"; import * as RuntimePolicy from "../RuntimePolicy.ts"; +import * as WorkspaceFolders from "../../workspace/WorkspaceFolders.ts"; import * as TurnItemPositionStore from "../TurnItemPositionStore.ts"; import * as RuntimeRequestService from "../RuntimeRequestService.ts"; import * as ThreadCommandExecutor from "../ThreadCommandExecutor.ts"; @@ -384,7 +385,13 @@ export function layerWithRegistry( Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); const layerCheckpointServiceProvided = CheckpointService.layer.pipe( - Layer.provide(Layer.mergeAll(layerCheckpointStore, IdAllocator.layer)), + Layer.provide( + Layer.mergeAll( + layerCheckpointStore, + IdAllocator.layer, + WorkspaceFolders.layer.pipe(Layer.provide(layerStores)), + ), + ), ); const layerContextHandoffServiceProvided = ContextHandoffService.layer.pipe( Layer.provide(IdAllocator.layer), diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 4084e531f2302..be5c4aa35fe7b 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1035,9 +1035,71 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ); + // Nested checkouts have their own checkpoints; unexcluded, the outer one records them as gitlinks. + const excludedPathspecs = (excludePaths: ReadonlyArray | undefined) => + (excludePaths ?? []).map((relativePath) => `:(exclude,literal)${relativePath}`); + + const checkpointIdentity: NodeJS.ProcessEnv = { + GIT_AUTHOR_NAME: "T3 Code", + GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", + GIT_COMMITTER_NAME: "T3 Code", + GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + }; + + // Index files known to hold no assume-unchanged or skip-worktree entry, by their stat. Setting + // either flag rewrites the index, so a matching stat spares the scan that looks for them. + const unflaggedIndexes = new Map(); + + // Status hides edits to assume-unchanged and skip-worktree entries; a capture reads them. + const hasFlaggedIndexEntries = Effect.fn("GitVcsDriver.hasFlaggedIndexEntries")(function* ( + cwd: string, + ) { + // A linked worktree keeps its index elsewhere; it is scanned every time. + const indexStat = yield* fileSystem.stat(path.join(cwd, ".git", "index")).pipe( + Effect.map((info) => + Option.isSome(info.mtime) ? `${info.mtime.value.getTime()}:${info.size}` : null, + ), + Effect.orElseSucceed(() => null), + ); + if (indexStat !== null && unflaggedIndexes.get(cwd) === indexStat) return false; + let flagged = false; + let recordStart = true; + yield* vcsProcess.run({ + operation: "GitVcsDriver.checkpoints.resolveCleanHead", + command: "git", + cwd, + args: ["ls-files", "-v", "-z"], + maxOutputBytes: 1, + outputMode: "truncate", + // Only each record's leading tag matters; scan NUL-delimited records. + onStdoutChunk: (chunk) => { + let start = 0; + while (start < chunk.length && !flagged) { + if (recordStart) { + const tag = chunk[start]!; + flagged = (tag >= 97 && tag <= 122) || tag === 83; + } + const end = chunk.indexOf(0, start); + recordStart = end !== -1; + if (!recordStart) break; + start = end + 1; + } + }, + }); + if (flagged) unflaggedIndexes.delete(cwd); + else if (indexStat !== null) unflaggedIndexes.set(cwd, indexStat); + return flagged; + }); + const checkpoints: VcsDriver.VcsCheckpointOps = { captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) { const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + // git add rejects a pathspec naming an ignored folder, and skips that folder anyway. + const exclusionPathspecs = excludedPathspecs( + input.excludePaths === undefined || input.excludePaths.length === 0 + ? undefined + : yield* filterIgnoredPaths(input.cwd, input.excludePaths), + ); // Scratch split-index writes can expire sharedindex files still used by the real index. const indexConfig = [ "-c", @@ -1064,13 +1126,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const indexId = yield* random.uuidV4(); const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`); const hostEnv = yield* HostProcess.Environment; - const commitEnv: NodeJS.ProcessEnv = { - GIT_INDEX_FILE: tempIndexPath, - GIT_AUTHOR_NAME: "T3 Code", - GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", - GIT_COMMITTER_NAME: "T3 Code", - GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", - }; + const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, ...checkpointIdentity }; const cleanupTempIndex = Effect.forEach( [tempIndexPath, `${tempIndexPath}.lock`], @@ -1332,6 +1388,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( workspaceIgnored ? "-u" : "-A", "--", ".", + ...exclusionPathspecs, ...exclusions, ], env: commitEnv, @@ -1574,6 +1631,61 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }).pipe(Effect.ensuring(cleanupTempIndex)); }), + resolveCleanHead: Effect.fn("GitVcsDriver.checkpoints.resolveCleanHead")(function* (cwd) { + // One status reads both, so a moving HEAD cannot pair one commit with another's cleanliness. + const status = yield* execute({ + operation: "GitVcsDriver.checkpoints.resolveCleanHead", + cwd, + args: [ + "-c", + "core.fsmonitor=false", + "status", + "--porcelain=v2", + "--branch", + "--untracked-files=normal", + "--ignore-submodules=none", + ], + // A status that refreshes the index would take the lock a user's Git command needs. + env: { GIT_OPTIONAL_LOCKS: "0" }, + maxOutputBytes: 4_096, + outputMode: "truncate", + }); + if (status.stdoutTruncated) return null; + const lines = status.stdout.split("\n").filter((line) => line.length > 0); + if (lines.some((line) => !line.startsWith("# "))) return null; + const head = lines.find((line) => line.startsWith("# branch.oid "))?.slice(13); + if (head === undefined || !/^[0-9a-f]{40,64}$/.test(head)) return null; + return (yield* hasFlaggedIndexEntries(cwd)) ? null : head; + }), + + captureHeadCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureHeadCheckpoint")( + function* (input) { + const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + const commit = yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...durableWrite, + "commit-tree", + `${input.head}^{tree}`, + "-p", + input.head, + "-m", + `t3 checkpoint ref=${input.checkpointRef}`, + ], + env: + input.seenAt === undefined + ? checkpointIdentity + : { ...checkpointIdentity, GIT_COMMITTER_DATE: `@${input.seenAt} +0000` }, + }); + yield* execute({ + operation, + cwd: input.cwd, + args: [...durableWrite, "update-ref", input.checkpointRef, commit.stdout.trim()], + }); + }, + ), + hasCheckpointRef: (input) => resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe( Effect.map((commit) => commit !== null), @@ -1780,6 +1892,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "checkpoint.fallback_from_to_head": input.fallbackFromToHead, }); + const diffExclusions = excludedPathspecs(input.excludePaths); let fromRevision = yield* resolveTurnStart(input); if (input.fallbackFromToHead === true) { const resolvedFromCommit = yield* resolveCheckpointCommit( @@ -1822,8 +1935,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( `${input.toCheckpointRef}^{commit}`, // Paths are repository-relative, while cwd can be a subdirectory. ...(input.filePaths - ? ["--", ...input.filePaths.map((file) => `:(top,literal)${file}`)] - : []), + ? ["--", ...input.filePaths.map((file) => `:(top,literal)${file}`), ...diffExclusions] + : diffExclusions.length > 0 + ? ["--", ":(top)", ...diffExclusions] + : []), ], allowNonZeroExit: true, maxOutputBytes: input.maxOutputBytes ?? VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, @@ -1897,13 +2012,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // A commit is an import when a fetch delivered it since the previous checkpoint and no // reflog in any worktree shows this repository creating it. --all covers every worktree's - // HEAD, and with --walk-reflogs --since compares each entry's own time. + // HEAD, and with --walk-reflogs --max-age compares each entry's own time. --since would + // guess at a date, and reads a timestamp before 1973 as the current time. const listImportedCommits = Effect.gen(function* () { const entries = (yield* listLines([ "log", "--walk-reflogs", "--all", - `--since=@${capturedAt}`, + `--max-age=${capturedAt}`, "--format=%H %gD %gs", ])).map((line) => { const [commit = "", selector = "", ...subject] = line.split(" "); @@ -1927,7 +2043,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( .map((entry) => entry.commit), ); const fetched = yield* listLines( - ["rev-list", `--since=@${capturedAt}`, "--stdin"], + ["rev-list", `--max-age=${capturedAt}`, "--stdin"], `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, ); return new Set(fetched.filter((commit) => !createdHere.has(commit))); @@ -1936,7 +2052,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. const [recentCommits, ...pathLists] = yield* Effect.all( [ - listLines(["rev-list", `--since=@${capturedAt}`, `${startHead}..${endHead}`]), + listLines(["rev-list", `--max-age=${capturedAt}`, `${startHead}..${endHead}`]), listPaths(["diff", startHead, `${turnStart}^{commit}`]), listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]), listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]), diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index 383db4302543f..8537dace4c559 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -16,6 +16,20 @@ export interface VcsCaptureCheckpointInput { readonly checkpointRef: CheckpointRef; /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */ readonly previousCheckpointRef?: CheckpointRef; + /** Folders below `cwd` (relative, `/`-separated) that other checkpoints own, such as nested clones. */ + readonly excludePaths?: ReadonlyArray; +} + +export interface VcsCaptureHeadCheckpointInput { + readonly cwd: string; + readonly checkpointRef: CheckpointRef; + /** A commit `resolveCleanHead` returned for this folder. */ + readonly head: string; + /** + * When the folder was seen clean, in epoch seconds, if that was earlier than now. Commits made + * after a checkpoint count as the turn's own work, so a late snapshot must not postdate them. + */ + readonly seenAt?: number; } export interface VcsRestoreCheckpointInput { @@ -37,6 +51,8 @@ export interface VcsDiffCheckpointsInput { readonly maxOutputBytes?: number; /** An empty list yields an empty diff. */ readonly filePaths?: ReadonlyArray; + /** Folders below `cwd` left out of the diff, as in a capture. */ + readonly excludePaths?: ReadonlyArray; } export interface VcsListAuthoredPathsInput { @@ -52,6 +68,15 @@ export interface VcsDeleteCheckpointRefsInput { export interface VcsCheckpointOps { readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect; + /** + * HEAD's commit when the folder matches it exactly: nothing staged, modified or untracked. + * Null otherwise. One status, where a capture stages the whole worktree. + */ + readonly resolveCleanHead: (cwd: string) => Effect.Effect; + /** Snapshots a folder that was clean at `head` from that commit, without reading its files. */ + readonly captureHeadCheckpoint: ( + input: VcsCaptureHeadCheckpointInput, + ) => Effect.Effect; readonly hasCheckpointRef: ( input: Omit, ) => Effect.Effect; diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 5b2822239af89..2bce9f4358fb8 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -135,6 +135,22 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { const missing = folder("gone", "gone"); const linked = folder("shared", "app", "linked"); const shared = path.join(tmp, "shared"); + const worktree = path.join(tmp, "tree"); + // `lib` is checked out with a submodule of its own; `docs` was never initialized. + const gitmodules = + '[submodule "lib"]\n\tpath = vendor/lib\n[submodule "docs"]\n\tpath = docs\n'; + for (const root of [workspaceRoot, worktree]) { + yield* fileSystem.makeDirectory(path.join(root, "vendor", "lib", "deep", ".git"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(root, "docs"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(root, "vendor", "lib", ".git"), "gitdir: x\n"); + yield* fileSystem.writeFileString(path.join(root, ".gitmodules"), gitmodules); + yield* fileSystem.writeFileString( + path.join(root, "vendor", "lib", ".gitmodules"), + '[submodule "deep"]\n\tpath = deep\n', + ); + } for (const directory of [inside.path, path.join(repository.path, ".git"), shared]) { yield* fileSystem.makeDirectory(directory, { recursive: true }); } @@ -159,9 +175,35 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { // A symlink inside the project folder still leads outside it. extraRoots: [repository.path, linked.path, shared], }); + assert.deepEqual(yield* workspaceFolders.forThread({ projectId, worktreePath: worktree }), { + folders: [], + extraRoots: [], + }); + assert.deepEqual(yield* workspaceFolders.submodules({ projectId, worktreePath: null }), [ + { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, + { + name: "deep", + path: path.join(workspaceRoot, "vendor", "lib", "deep"), + isGitRepository: true, + }, + ]); + // A worktree reaches its own submodules, named by where the project folder has them. assert.deepEqual( - yield* workspaceFolders.forThread({ projectId, worktreePath: path.join(tmp, "tree") }), - { folders: [], extraRoots: [] }, + yield* workspaceFolders.submodules({ projectId, worktreePath: worktree }), + [ + { + name: "lib", + path: path.join(worktree, "vendor", "lib"), + isGitRepository: true, + repositoryPath: path.join(workspaceRoot, "vendor", "lib"), + }, + { + name: "deep", + path: path.join(worktree, "vendor", "lib", "deep"), + isGitRepository: true, + repositoryPath: path.join(workspaceRoot, "vendor", "lib", "deep"), + }, + ], ); }).pipe( Effect.provide( diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index aa6e88ef36c12..8ab00715a72bf 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -28,6 +28,8 @@ export interface ThreadFolder { readonly name: string; readonly path: string; readonly isGitRepository: boolean; + /** The folder `path` is a checkout of. Absent when `path` is that folder. */ + readonly repositoryPath?: string; } export interface ThreadWorkspace { @@ -37,6 +39,8 @@ export interface ThreadWorkspace { } const EMPTY_WORKSPACE: ThreadWorkspace = { folders: [], extraRoots: [] }; +// Each one costs a status per turn. +const THREAD_SUBMODULES_MAX = 32; export class WorkspaceFolders extends Context.Service< WorkspaceFolders, @@ -49,6 +53,14 @@ export class WorkspaceFolders extends Context.Service< readonly projectId: ProjectId; readonly worktreePath: string | null; }) => Effect.Effect; + /** + * Submodules checked out inside the thread's cwd or its folders. Their repository owns how + * they get there, so they are reviewed like the folders but never granted or announced. + */ + readonly submodules: (input: { + readonly projectId: ProjectId; + readonly worktreePath: string | null; + }) => Effect.Effect, WorkspaceFoldersError>; readonly list: ( input: WorkspaceListFoldersInput, ) => Effect.Effect; @@ -77,7 +89,7 @@ const decodeCodeWorkspace = Schema.decodeUnknownEffect( ); /** Submodule paths a `.gitmodules` file declares, relative to its folder with `/` separators. */ -const parseGitmodulesPaths = (text: string): ReadonlyArray => +export const parseGitmodulesPaths = (text: string): ReadonlyArray => text.split(/\r?\n/).flatMap((line) => { const value = /^\s*path\s*=\s*(.*?)\s*$/.exec(line)?.[1]; if (value === undefined) return []; @@ -216,7 +228,7 @@ const make = Effect.gen(function* () { const path = yield* Path.Path; const projects = yield* ProjectStore.ProjectStoreV2; - const { realPath, classify } = yield* folderProbes; + const { exists, realPath, classify } = yield* folderProbes; const readProject = Effect.fn("WorkspaceFolders.readProject")(function* (projectId: ProjectId) { const row = yield* projects @@ -238,6 +250,61 @@ const make = Effect.gen(function* () { const classifyAll = (folders: ReadonlyArray) => Effect.forEach(folders, classify, { concurrency: DETECTION_CONCURRENCY }); + // `identity` is `root` in the checkout the thread's was made from: it names the same submodule + // in every worktree. + const submodulesBelow = (root: { + readonly path: string; + readonly identity: string; + }): Effect.Effect> => + fileSystem.readFileString(path.join(root.path, ".gitmodules")).pipe( + Effect.orElseSucceed(() => ""), + Effect.flatMap((text) => + Effect.forEach( + parseGitmodulesPaths(text), + (relative) => { + const folder = path.resolve(root.path, relative); + const identity = path.resolve(root.identity, relative); + if (folder === root.path || !isWithinRoot(path, folder, root.path)) { + return Effect.succeed([]); + } + // One that was never initialized is an empty folder. + return exists(path.join(folder, ".git")).pipe( + Effect.flatMap((present) => + present + ? submodulesBelow({ path: folder, identity }).pipe( + Effect.map((nested) => [ + { + name: path.basename(folder), + path: folder, + isGitRepository: true, + ...(identity === folder ? {} : { repositoryPath: identity }), + }, + ...nested, + ]), + ) + : Effect.succeed([]), + ), + ); + }, + { concurrency: DETECTION_CONCURRENCY }, + ), + ), + Effect.map((found) => found.flat()), + ); + + const submodulesOf = Effect.fnUntraced(function* ( + roots: ReadonlyArray<{ readonly path: string; readonly identity: string }>, + ) { + const found = yield* Effect.forEach(roots, submodulesBelow, { + concurrency: DETECTION_CONCURRENCY, + }); + const taken = new Set(roots.map((root) => root.path)); + return found + .flat() + .filter((folder) => !taken.has(folder.path)) + .slice(0, THREAD_SUBMODULES_MAX); + }); + const forThread: WorkspaceFolders["Service"]["forThread"] = Effect.fn( "WorkspaceFolders.forThread", )(function* (input) { @@ -262,6 +329,29 @@ const make = Effect.gen(function* () { return { folders, extraRoots: [...new Set(outside.flat())] }; }); + const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn( + "WorkspaceFolders.submodules", + )(function* (input) { + const { folders } = yield* forThread(input); + // A worktree can outlive its project record; its submodules are then named by where they are. + const projectRoot = yield* readProject(input.projectId).pipe( + Effect.map((project) => path.resolve(project.workspaceRoot)), + Effect.option, + ); + const own = input.worktreePath === null ? null : path.resolve(input.worktreePath); + const root = own ?? Option.getOrNull(projectRoot); + if (root === null) return []; + const identity = Option.getOrElse(projectRoot, () => root); + return yield* submodulesOf([ + { path: root, identity }, + ...folders.flatMap((folder) => + folder.isGitRepository + ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }] + : [], + ), + ]); + }); + const list: WorkspaceFolders["Service"]["list"] = Effect.fn("WorkspaceFolders.list")( function* (input) { return { folders: yield* classifyAll((yield* readProject(input.projectId)).trackedFolders) }; @@ -274,7 +364,7 @@ const make = Effect.gen(function* () { Effect.provideService(Path.Path, path), ); - return WorkspaceFolders.of({ forThread, list, scan }); + return WorkspaceFolders.of({ forThread, submodules, list, scan }); }); export const layer = Layer.effect(WorkspaceFolders, make); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 8aa4df4c09ba5..714be689a3a46 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -8,6 +8,7 @@ import { withMessageContext, deriveAvailableRevertTurnCounts, deriveThreadPendingBackgroundTasks, + resolveProactiveTurnDiffAction, } from "./ChatView.logic"; import { isThreadEnvironmentLocked, @@ -23,6 +24,7 @@ import { terminalContextReference, } from "../lib/composerContextRecords"; import { + CheckpointScopeId, CommandId, EnvironmentId, MessageId, @@ -1236,6 +1238,54 @@ describe("boundAttachmentIds", () => { }); }); +describe("resolveProactiveTurnDiffAction", () => { + const file = { path: "src/a.ts", kind: "modified", additions: 60, deletions: 0 }; + const repository = (files: ReadonlyArray) => ({ + scopeId: CheckpointScopeId.make("scope-api"), + name: "api", + repositoryPath: "/work/api", + cwd: "/work/api", + files, + baselineMissing: files.length === 0, + }); + + it("opens for repository changes in a folder that is not a Git repository", () => { + expect( + resolveProactiveTurnDiffAction({ + checkpoint: { status: "missing", files: [], repositories: [repository([file])] }, + isGitRepo: false, + }), + ).toBe("open"); + expect( + resolveProactiveTurnDiffAction({ + checkpoint: { status: "missing", files: [], repositories: [repository([])] }, + isGitRepo: false, + }), + ).toBe("ignore"); + }); + + it("keeps waiting on a missing checkpoint and ignores a folder without Git", () => { + expect( + resolveProactiveTurnDiffAction({ + checkpoint: { status: "missing", files: [] }, + isGitRepo: true, + }), + ).toBe("defer"); + expect( + resolveProactiveTurnDiffAction({ + checkpoint: { status: "ready", files: [file] }, + isGitRepo: false, + }), + ).toBe("ignore"); + expect( + resolveProactiveTurnDiffAction({ + checkpoint: { status: "ready", files: [file] }, + isGitRepo: true, + }), + ).toBe("open"); + }); +}); + describe("deriveAvailableRevertTurnCounts", () => { const providerThreadId = ProviderThreadId.make("provider-thread"); const otherProviderThreadId = ProviderThreadId.make("other-provider-thread"); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 92a456f12d308..f92cbecc3e4e8 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -4,7 +4,7 @@ import { deriveLatestThreadRun, deriveThreadRuntime, } from "@t3tools/client-runtime/state/thread-execution"; -import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { turnChanges } from "@t3tools/client-runtime/state/thread-repositories"; import { COMPACT_COMMAND_PATTERN } from "@t3tools/client-runtime/state/context-window"; import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { @@ -217,19 +217,22 @@ export function shouldOpenProactiveTurnDiff(input: { } export function resolveProactiveTurnDiffAction(input: { - checkpoint: Pick | undefined; + checkpoint: Pick | undefined; isGitRepo: boolean | undefined; }): "defer" | "ignore" | "open" { - if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer"; - if (input.isGitRepo === undefined) return "defer"; - if ( - !input.isGitRepo || - input.checkpoint.status !== "ready" || - input.checkpoint.files.length === 0 - ) { - return "ignore"; + // A turn that changed tracked repositories has a diff whatever the thread's own folder is. + if (input.checkpoint?.repositories === undefined) { + if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer"; + if (input.isGitRepo === undefined) return "defer"; + if ( + !input.isGitRepo || + input.checkpoint.status !== "ready" || + input.checkpoint.files.length === 0 + ) { + return "ignore"; + } } - const totals = checkpointFileTotals(input.checkpoint); + const { totals } = turnChanges(input.checkpoint); return totals.count >= 3 || totals.additions + totals.deletions >= 50 ? "open" : "ignore"; } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9242d934169f1..15b889b78f00f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1640,8 +1640,7 @@ export default function ChatView(props: ChatViewProps) { const availableRevertTurnCounts = deriveAvailableRevertTurnCounts(serverProjection); // A paged history window cannot identify the first loaded run as the thread start. const threadStartCheckpointAvailable = - !serverThreadHistory.hasMoreHistory && - findRevertCheckpoint(serverProjection?.checkpoints ?? [], 0) !== undefined; + !serverThreadHistory.hasMoreHistory && findRevertCheckpoint(serverProjection, 0) !== undefined; const workspaceMutationId = deriveWorkspaceMutationId( serverVisibleTurnItems, @@ -1752,6 +1751,9 @@ export default function ChatView(props: ChatViewProps) { } }, [environmentId, gitStatusCwd, liveIsGitRepo]); const isGitRepo = liveIsGitRepo ?? recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? true; + // A plain folder holding tracked repositories has turn diffs without being a Git repository. + const diffAvailable = + isGitRepo || turnDiffSummaries.some((summary) => summary.repositories !== undefined); // Provider-native subagents cannot take messages; approvals and questions go to the top-level parent. const showProviderSubagentBar = isProviderSubagent; const composerMounted = !showProviderSubagentBar; @@ -2406,7 +2408,7 @@ export default function ChatView(props: ChatViewProps) { threadPanelPresentation, isServerThread, embedded, - isGitRepo, + diffAvailable, browserAvailable, canOperatePreview, diffOpen, @@ -4022,7 +4024,7 @@ export default function ChatView(props: ChatViewProps) { onAddSideChat={sideChatsOffered ? openSideChatStable : undefined} browserAvailable={canOperatePreview && browserAvailable} terminalAvailable={activeProject !== null && canOperateTerminal} - diffAvailable={isServerThread && isGitRepo} + diffAvailable={isServerThread && diffAvailable} filesAvailable={activeProject !== null} pullRequestAvailable={pullRequestSurfaceAvailable} pullRequestsAvailable={pullRequestsSurfaceAvailable} @@ -4036,7 +4038,7 @@ export default function ChatView(props: ChatViewProps) { @@ -4050,6 +4052,7 @@ export default function ChatView(props: ChatViewProps) { threadRef={activeThreadRef} cwd={activeWorkspaceRoot} checkpoints={serverProjection?.checkpoints} + checkpointScopes={serverProjection?.checkpointScopes} > {content} diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 51ba65933dff7..b52ee315beb35 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -3,10 +3,13 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { DEFAULT_CLIENT_SETTINGS, EnvironmentId, + CheckpointRef, + CheckpointScopeId, ProjectId, RunId, ThreadId, type ClientSettings, + type OrchestrationGetTurnDiffResult, type ReviewBranchCommitsResult, type ReviewDiffPreviewResult, type ReviewDiffPreviewSource, @@ -37,7 +40,7 @@ const state = vi.hoisted(() => ({ remoteRefs: null as unknown as ResultAtom, commits: null as unknown as ResultAtom, checkpoints: [] as unknown[], - checkpointDiff: null as { diff: string } | null, + checkpointDiff: null as Partial | null, })); vi.mock("~/state/server", () => ({ @@ -302,3 +305,80 @@ it("says a turn diff cut off at the server's size limit is incomplete", async () .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete.")) .toBeVisible(); }); + +it("shows a turn's repositories in a folder that is not a Git repository", async () => { + using context = setup("origin/orphan"); + state.status = Atom.make( + AsyncResult.success({ + isRepo: false, + hasPrimaryRemote: false, + isDefaultRef: false, + refName: null, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ); + const patch = (path: string) => + `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-before\n+after\n`; + const repository = (name: string) => ({ + scopeId: CheckpointScopeId.make(`scope-${name}`), + name, + repositoryPath: `${cwd}/${name}`, + cwd: `${cwd}/${name}`, + relativePath: name, + files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }], + baselineMissing: false, + }); + state.checkpoints = [ + { + runId: RunId.make("run-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("refs/t3/root-1"), + status: "missing", + files: [], + repositories: [repository("api"), repository("web")], + assistantMessageId: null, + completedAt: "2026-11-10T00:00:00.000Z", + }, + ]; + state.checkpointDiff = { + threadId: context.threadRef.threadId, + fromTurnCount: 0, + toTurnCount: 1, + diff: "", + repositories: ["api", "web"].map((name) => ({ + name, + repositoryPath: `${cwd}/${name}`, + relativePath: name, + diff: patch("README.md"), + })), + }; + await using screen = await render( + +
+ +
+
, + ); + const api = screen.getByRole("button", { name: "Collapse api/README.md", exact: true }); + const web = screen.getByRole("button", { name: "Collapse web/README.md", exact: true }); + await expect.element(api).toBeVisible(); + await expect.element(web).toBeVisible(); + // Both pickers keep their labels in a phone-width panel. + await expect.element(screen.getByText("Latest turn", { exact: true })).toBeVisible(); + const picker = screen.getByRole("button", { name: "Repository: All repositories" }); + await expect.element(picker.getByText("All repositories")).toBeVisible(); + await userEvent.click(picker); + await userEvent.click(page.getByRole("menuitemradio", { name: "web" })); + await expect.element(web).toBeVisible(); + await expect.element(api).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 2b0a6a78d4ec2..6c437a347559b 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -40,6 +40,7 @@ import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries"; import { revisionedQuery } from "~/state/revisionedQuery"; import { cn } from "~/lib/utils"; import { + type DiffPanelSelection, resolveToolCallDiffTarget, selectThreadBranchBaseRef, selectThreadDiffPanelSelection, @@ -56,6 +57,7 @@ import { buildFileDiffIdentityKey, getDiffLineStat, getRenderablePatch, + getRenderablePatchSections, resolveDiffThemeName, resolveFileDiffPath, } from "../lib/diffRendering"; @@ -115,10 +117,17 @@ import { DiffFileLoadingBoundary } from "./diffs/DiffFileLoadingBoundary"; import { DiffFileStatus } from "./diffs/DiffFileStatus"; import { useThreadRouteRef } from "../hooks/useThreadRouteTarget"; import { projectCommitUrl } from "@t3tools/client-runtime/change-request-links"; +import { + repositorySectionForPath, + turnDiffSections, + type TurnDiffSection, +} from "@t3tools/client-runtime/state/thread-repositories"; import { useOpenLink } from "../browser/useOpenLink"; type DiffThemeType = "light" | "dark"; const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; +const ALL_REPOSITORIES = "__all_repositories__"; +const NO_TURN_DIFF_SECTIONS: ReadonlyArray = []; const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen"; const fileEntryCache = new WeakMap< FileDiffMetadata, @@ -287,9 +296,31 @@ export default function DiffPanel({ }) : null, ); - const diffSelection = useDiffPanelStore((state) => + const storedDiffSelection = useDiffPanelStore((state) => selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), ); + const isGitRepo = gitStatusQuery.data?.isRepo ?? true; + const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); + const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { + if (left.checkpointTurnCount !== right.checkpointTurnCount) { + return right.checkpointTurnCount - left.checkpointTurnCount; + } + return right.completedAt.localeCompare(left.completedAt); + }); + const latestTurn = orderedTurnDiffSummaries[0]; + const hasRepositoryChanges = turnDiffSummaries.some( + (summary) => summary.repositories !== undefined, + ); + // A plain folder holding tracked repositories has no branch or working tree of its own; every + // way into the panel lands on its latest turn. + const turnDiffsOnly = !isGitRepo && hasRepositoryChanges; + const diffSelection: DiffPanelSelection = + turnDiffsOnly && + latestTurn !== undefined && + storedDiffSelection.kind !== "turn" && + storedDiffSelection.kind !== "tool-call" + ? { kind: "turn", turnId: latestTurn.runId, filePath: null, revealRequestId: 0 } + : storedDiffSelection; const rememberedBaseRef = useDiffPanelStore((state) => selectThreadBranchBaseRef(state, routeThreadRef), ); @@ -308,23 +339,15 @@ export default function DiffPanel({ : null, ); const toolCallItem = toolCallDetail.data?.item; - const isGitRepo = gitStatusQuery.data?.isRepo ?? true; - const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); - const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { - if (left.checkpointTurnCount !== right.checkpointTurnCount) { - return right.checkpointTurnCount - left.checkpointTurnCount; - } - return right.completedAt.localeCompare(left.completedAt); - }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rewrites the persisted diff store selection to the latest turn when the selected turn disappears useEffect(() => { - if (!routeThreadRef || diffSelection.kind !== "turn") return; + if (!routeThreadRef || storedDiffSelection.kind !== "turn") return; useDiffPanelStore.getState().reconcileTurnSelection( routeThreadRef, orderedTurnDiffSummaries.map((summary) => summary.runId), ); - }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]); + }, [storedDiffSelection, orderedTurnDiffSummaries, routeThreadRef]); const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null; const selectedGitScope = @@ -345,7 +368,6 @@ export default function DiffPanel({ : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ?? orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount; - const latestTurn = orderedTurnDiffSummaries[0]; const reviewSectionId = toolCallSelection ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` : selectedTurn @@ -373,7 +395,7 @@ export default function DiffPanel({ ignoreWhitespace: diffIgnoreWhitespace, cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null, }, - { enabled: isGitRepo && selectedTurn !== undefined }, + { enabled: (isGitRepo || hasRepositoryChanges) && selectedTurn !== undefined }, ); const branchDiffPreviewInput = canReadFiles && isGitSelection && activeThread && activeCwd @@ -481,10 +503,25 @@ export default function DiffPanel({ const toolCallPreview = toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null; + const turnSections = + selectedTurn && activeCheckpointDiff.data + ? turnDiffSections(activeCheckpointDiff.data, activeProject?.title ?? "Project folder") + : NO_TURN_DIFF_SECTIONS; + // Sections only matter when a repository changed; otherwise the turn has its one patch. + const repositorySections = turnSections.some((section) => section.repositoryPath !== null) + ? turnSections + : NO_TURN_DIFF_SECTIONS; + const repositoryFilter = + diffSelection.kind === "turn" ? (diffSelection.repository ?? null) : null; + const selectedSection = + repositorySections.find((section) => section.key === repositoryFilter) ?? null; + const shownSections = selectedSection ? [selectedSection] : repositorySections; const selectedPatch = toolCallSelection ? toolCallPreview?.patch : selectedTurn - ? activeCheckpointDiff.data?.diff + ? shownSections.length > 0 + ? shownSections.map((section) => section.diff).join("\n") + : activeCheckpointDiff.data?.diff : gitDiff; const isSelectedPatchTruncated = toolCallPreview?.truncated === true || @@ -518,14 +555,13 @@ export default function DiffPanel({ selectedGitSource.files?.length ? selectedGitSource : null; - const renderablePatch = getRenderablePatch( - lazySource ? undefined : selectedPatch, - `diff-panel:${resolvedTheme}`, - { - compactPartialHunkOffsets: isGitSelection, - ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}), - }, - ); + const renderablePatch = + shownSections.length > 0 + ? getRenderablePatchSections(shownSections, `diff-panel:${resolvedTheme}`) + : getRenderablePatch(lazySource ? undefined : selectedPatch, `diff-panel:${resolvedTheme}`, { + compactPartialHunkOffsets: isGitSelection, + ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}), + }); const recordedToolCallFileCount = toolCallSelection && toolCallItem?.type === "file_change" ? (toolCallItem.changes?.length ?? 0) @@ -750,12 +786,27 @@ export default function DiffPanel({ } }, [collapseScopeKey, selectedFilePath, selectedFileRevealRequestId, revealDiffFile]); + // A tracked repository's file is named from the thread's folder; on disk it belongs to the + // repository's own folder, which may sit outside the thread's. + const repositoryFileTarget = (filePath: string) => { + const match = repositorySectionForPath(repositorySections, filePath); + if (match === null) return null; + return { + path: match.path, + insideThreadFolder: !match.section.relativePath.startsWith(".."), + cwd: selectedTurn?.repositories?.find( + (repository) => repository.repositoryPath === match.section.repositoryPath, + )?.cwd, + }; + }; const openDiffFile = (filePath: string) => { + const repositoryFile = repositoryFileTarget(filePath); openDiffFilePrimaryAction({ - threadRef: routeThreadRef, - filePath, - activeCwd, - repositoryRoot: activeRepositoryRoot, + // The file viewer reads below the thread's folder; a repository outside it opens in the editor. + threadRef: repositoryFile?.insideThreadFolder === false ? null : routeThreadRef, + filePath: repositoryFile?.insideThreadFolder === false ? repositoryFile.path : filePath, + activeCwd: repositoryFile?.insideThreadFolder === false ? repositoryFile.cwd : activeCwd, + repositoryRoot: repositoryFile ? undefined : activeRepositoryRoot, openInEditor: (targetPath) => { void (async () => { const result = await openInPreferredEditor(targetPath); @@ -826,6 +877,16 @@ export default function DiffPanel({ : selectedTurn?.runId === latestTurn?.runId ? "latest" : selectedTurnValue; + const selectRepository = (key: string) => { + if (!routeThreadRef || !selectedTurn) return; + useDiffPanelStore + .getState() + .selectTurnRepository( + routeThreadRef, + selectedTurn.runId, + key === ALL_REPOSITORIES ? null : key, + ); + }; const selectScopeValue = (value: string) => { if (value === "unstaged" || value === "branch") { selectGitScope(value); @@ -843,13 +904,20 @@ export default function DiffPanel({ } }; + // Two pickers leave no room for these in a phone-width panel, where a split view cannot fit anyway. + const narrowHeaderHidden = + repositorySections.length > 0 ? "@max-[30rem]/diff-header:hidden" : undefined; const headerRow = ( <>
} - className={cn("max-w-full", headerCommitSha !== null && "min-w-0 shrink")} + className={cn( + "max-w-full", + headerCommitSha !== null && "min-w-0 shrink", + repositorySections.length > 0 && "min-w-14 shrink", + )} aria-label={`Diff scope: ${selectedScopeLabel}`} data-workspace-focus-default > @@ -882,12 +950,16 @@ export default function DiffPanel({ ) : null} - - Changes - - - Uncommitted - + {turnDiffsOnly ? null : ( + <> + + Changes + + + Uncommitted + + + )} Latest turn @@ -916,101 +988,137 @@ export default function DiffPanel({ - { - setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null); - if (!open) return; - // The menu keeps the list it opened with; the refreshed one shows next time. - branchCommitsQuery.refresh(); - }} - > - Commits - - - {branchCommits?.commits.map((commit) => { - const commitUrl = projectCommitUrl( - activeProject?.repositoryIdentity, - commit.sha, - ); - return ( -
- - - } - > - - {commit.subject} - - {formatRelativeTimeLabel(commit.committedAt)} + {turnDiffsOnly ? null : ( + { + setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null); + if (!open) return; + // The menu keeps the list it opened with; the refreshed one shows next time. + branchCommitsQuery.refresh(); + }} + > + Commits + + + {branchCommits?.commits.map((commit) => { + const commitUrl = projectCommitUrl( + activeProject?.repositoryIdentity, + commit.sha, + ); + return ( +
+ + + } + > + + {commit.subject} + + {formatRelativeTimeLabel(commit.committedAt)} + - - - - {commit.subject} - - - {commitUrl ? ( - - } - onClick={(event) => openCommitUrl(event, commitUrl)} - > - + + + {commit.subject} + + + {commitUrl ? ( + + } + onClick={(event) => openCommitUrl(event, commitUrl)} + > + + {commit.sha.slice(0, 7)} + + + ) : ( + {commit.sha.slice(0, 7)} - - ) : ( - - {commit.sha.slice(0, 7)} - - )} -
- ); - })} -
- {branchCommitsQuery.error ? ( - {branchCommitsQuery.error} - ) : !canReadFiles ? ( - - {fileAccess.isPending - ? "Checking file access..." - : (fileAccess.error ?? "This connection cannot read local diffs.")} - - ) : branchCommits === null ? ( - Loading commits... - ) : branchCommits.commits.length === 0 ? ( - No commits on this branch. - ) : branchCommits.truncated ? ( - - {`Showing latest ${branchCommits.commits.length} commits`} - - ) : null} -
-
+ )} +
+ ); + })} +
+ {branchCommitsQuery.error ? ( + {branchCommitsQuery.error} + ) : !canReadFiles ? ( + + {fileAccess.isPending + ? "Checking file access..." + : (fileAccess.error ?? "This connection cannot read local diffs.")} + + ) : branchCommits === null ? ( + Loading commits... + ) : branchCommits.commits.length === 0 ? ( + No commits on this branch. + ) : branchCommits.truncated ? ( + + {`Showing latest ${branchCommits.commits.length} commits`} + + ) : null} +
+
+ )}
+ {repositorySections.length > 0 && ( + + } + className="min-w-14 max-w-48 shrink" + aria-label={`Repository: ${selectedSection?.name ?? "All repositories"}`} + > + {selectedSection?.name ?? "All repositories"} + + + + + + All repositories + + {repositorySections.map((section) => ( + + + {section.name} + {section.relativePath !== "" && section.relativePath !== section.name ? ( + + {section.relativePath} + + ) : null} + + + ))} + + + + )} {canSelectBranchBase && (
{codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? ( - + + + ) : null} {canRefreshGitDiff && ( @@ -1199,25 +1309,27 @@ export default function DiffPanel({ )} - { - const next = value[0]; - if (next === "stacked" || next === "split") { - updateClientSettings({ diffLayout: next }); - } - }} - > - - - - - - - + + { + const next = value[0]; + if (next === "stacked" || next === "split") { + updateClientSettings({ diffLayout: next }); + } + }} + > + + + + + + + + Select a thread to inspect turn diffs.
- ) : !isGitRepo && !toolCallSelection ? ( + ) : !isGitRepo && !hasRepositoryChanges && !toolCallSelection ? (
Turn diffs are unavailable because this project is not a git repository.
@@ -1442,13 +1554,20 @@ export default function DiffPanel({ const filePath = title?.textContent?.trim(); if (!filePath) return; event.preventDefault(); + const repositoryFile = repositoryFileTarget(filePath); onFileContextMenu( - { - environmentId: activeThread?.environmentId ?? null, - filePath, - workspaceRoot: activeCwd, - repositoryRoot: activeRepositoryRoot, - }, + repositoryFile?.cwd === undefined + ? { + environmentId: activeThread?.environmentId ?? null, + filePath, + workspaceRoot: activeCwd, + repositoryRoot: repositoryFile ? undefined : activeRepositoryRoot, + } + : { + environmentId: activeThread?.environmentId ?? null, + filePath: repositoryFile.path, + workspaceRoot: repositoryFile.cwd, + }, event, ); }} diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index 456f70516b23b..effdb04b9f06a 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -10,7 +10,7 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar" | "embedded"; function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) { const shouldUseDragRegion = isElectron && mode !== "sheet" && mode !== "embedded"; return cn( - "flex items-center justify-between gap-2", + "@container/diff-header flex items-center justify-between gap-2", mode === "embedded" ? "px-2" : "px-4", shouldUseDragRegion ? "drag-region h-[var(--workspace-topbar-height)] border-b border-border wco:pr-(--workspace-native-controls-inset)" diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 5023da3a7823f..e8dac863b4426 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -9,6 +9,7 @@ import { ChevronsDownUpIcon, ChevronsUpDownIcon, FolderClosedIcon, + FolderGit2Icon, FolderIcon, } from "lucide-react"; import { cn } from "~/lib/utils"; @@ -18,6 +19,7 @@ import { Button } from "../ui/button"; 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"; const EMPTY_DIRECTORY_OVERRIDES: Record = {}; const VIRTUALIZE_AFTER_ROWS = 250; @@ -28,13 +30,38 @@ interface ChangedFileRow { depth: number; } -type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void; +/** One folder's share of a turn that changed several repositories. */ +export interface ChangedFilesGroup { + readonly key: string; + readonly name: string; + /** Paths relative to this group's folder. */ + readonly files: ReadonlyArray; + readonly totals: OrchestrationV2CheckpointFileTotals; + /** The folder from the thread's folder; undefined when the diff cannot be opened at a file. */ + readonly relativePath: string | undefined; + /** Shown in place of the files when they cannot be listed. */ + readonly note?: string | undefined; +} + +type ChangedFileContextMenuHandler = ( + filePath: string, + event: MouseEvent, + group?: ChangedFilesGroup, +) => void; + +function groupDiffPath(group: ChangedFilesGroup, filePath: string | undefined) { + return filePath === undefined || group.relativePath === undefined + ? undefined + : repositoryFilePath(group.relativePath, filePath); +} export const ChangedFilesCard = memo(function ChangedFilesCard(props: { runId: RunId; /** May be a prefix of the changed files; `totals` covers all of them. */ files: ReadonlyArray; totals: OrchestrationV2CheckpointFileTotals; + /** Set when the turn changed tracked repositories; replaces the single tree built from `files`. */ + groups?: ReadonlyArray | undefined; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; onToggleAllDirectories: () => void; @@ -45,6 +72,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { runId, files, totals, + groups, allDirectoriesExpanded, resolvedTheme, onToggleAllDirectories, @@ -52,8 +80,13 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { onFileContextMenu, } = props; const syncTimelineLayout = useSyncLayout(); - const hiddenFileCount = totals.count - files.length; - const hasDirectories = files.some((file) => /[/\\]/.test(file.path)); + const listedFiles = groups ? groups.flatMap((group) => group.files) : files; + const hiddenFileCount = totals.count - listedFiles.length; + const hasDirectories = listedFiles.some((file) => /[/\\]/.test(file.path)); + const firstGroup = groups?.find((group) => group.files.length > 0); + const firstFilePath = groups + ? firstGroup && groupDiffPath(firstGroup, firstGroup.files[0]?.path) + : files[0]?.path; return (
onOpenTurnDiff(runId, files[0]?.path)} + onClick={() => onOpenTurnDiff(runId, firstFilePath)} /> } > @@ -127,22 +160,38 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
- +
+ {groups ? ( + groups.map((group) => ( + + )) + ) : ( + + )} +
{hiddenFileCount > 0 && (
+ {collapsed ? null : group.note !== undefined ? ( +

{group.note}

+ ) : ( + onOpenTurnDiff(run, groupDiffPath(group, filePath))} + onFileContextMenu={ + onFileContextMenu + ? (filePath, event) => onFileContextMenu(filePath, event, group) + : undefined + } + /> + )} + + ); +} + const ChangedFilesTree = memo(function ChangedFilesTree(props: { runId: RunId; files: ReadonlyArray; + /** Rows start this deep, below the row of the folder the files belong to. */ + baseDepth?: number; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onFileContextMenu?: ChangedFileContextMenuHandler | undefined; }) { + const baseDepth = props.baseDepth ?? 0; const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } = props; // Place state before tree derivation to preserve its compiler cache. @@ -197,7 +310,7 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { const virtualized = rows.length > VIRTUALIZE_AFTER_ROWS; const renderRow = ({ node, depth }: ChangedFileRow) => { - const leftPadding = 8 + depth * 14; + const leftPadding = 8 + (baseDepth + depth) * 14; if (node.kind === "directory") { const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded; return ( @@ -250,7 +363,7 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { : undefined } > - {hasDirectoryNodes || depth > 0 ? ( + {hasDirectoryNodes || baseDepth + depth > 0 ? (