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] 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)