Skip to content

Commit 0141bc2

Browse files
feat(settings): choose how new worktrees initialize submodules (pingdotgg#12955)
Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 742173a commit 0141bc2

18 files changed

Lines changed: 331 additions & 55 deletions

‎apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
type ServerSettings,
77
type ServerSettingsPatch,
88
type ThreadEnvMode,
9+
type WorktreeSubmodules,
910
PROJECT_SCOPED_SERVER_SETTING_KEYS,
1011
type ProjectScopedServerSettingKey,
1112
} from "@t3tools/contracts";
@@ -43,12 +44,32 @@ const PAGE_TITLES: Record<SettingsPage, string> = {
4344
};
4445

4546
const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettingKey[]> = {
46-
"new-threads": ["defaultThreadEnvMode", "defaultRuntimeMode"],
47+
"new-threads": ["defaultThreadEnvMode", "worktreeSubmodules", "defaultRuntimeMode"],
4748
"source-control": ["defaultAutoPull", "newWorktreesStartFromOrigin"],
4849
"agent-behavior": ["responseStreamingMode", "enableAgentBrowserAccess"],
4950
maintenance: ["continueThreadsAfterServerUpdate"],
5051
};
5152

53+
const SUBMODULE_CHOICES: ReadonlyArray<{
54+
readonly mode: WorktreeSubmodules | null;
55+
readonly label: string;
56+
readonly description: string;
57+
}> = [
58+
// Only offered at environment scope; a project falls back through "Use defaults".
59+
{
60+
mode: null,
61+
label: "Inherit",
62+
description: "Use the repository's t3.json, or initialize recursively.",
63+
},
64+
{ mode: "recursive", label: "Recursive", description: "Initialize nested submodules too." },
65+
{
66+
mode: "top-level",
67+
label: "Top level only",
68+
description: "Skip submodules declared inside other submodules.",
69+
},
70+
{ mode: "none", label: "Skip", description: "Leave submodules empty for a setup script." },
71+
];
72+
5273
const WORKSPACE_CHOICES: ReadonlyArray<{
5374
readonly mode: ThreadEnvMode | null;
5475
readonly label: string;
@@ -251,6 +272,31 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
251272
/>
252273
))}
253274
</SettingsSection>
275+
<SettingsSection
276+
title="Worktree submodules"
277+
trailing={
278+
pendingWrites === 0 && isMixed("worktreeSubmodules") ? (
279+
<MixedValuesLabel projectSelected={projectSelected} />
280+
) : null
281+
}
282+
>
283+
{SUBMODULE_CHOICES.filter(
284+
(choice) => choice.mode !== null || !projectSelected,
285+
).map((choice, index) => (
286+
<ChoiceRow
287+
key={choice.mode ?? "inherit"}
288+
label={choice.label}
289+
description={choice.description}
290+
selected={
291+
!isMixed("worktreeSubmodules") &&
292+
uniform("worktreeSubmodules") === choice.mode
293+
}
294+
separated={index > 0}
295+
disabled={disabledFor("worktreeSubmodules")}
296+
onPress={() => write({ worktreeSubmodules: choice.mode })}
297+
/>
298+
))}
299+
</SettingsSection>
254300
<SettingsSection
255301
title="Default permissions"
256302
trailing={

‎apps/server/src/git/GitManager.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2543,11 +2543,20 @@ export const make = Effect.gen(function* () {
25432543
});
25442544
}
25452545

2546-
const worktree = yield* gitCore.createWorktree({
2547-
cwd: input.cwd,
2548-
refName: localPullRequestBranch,
2549-
path: null,
2550-
});
2546+
const worktree = yield* gitCore.createWorktree(
2547+
{
2548+
cwd: input.cwd,
2549+
refName: localPullRequestBranch,
2550+
path: null,
2551+
},
2552+
{
2553+
// Best effort: a settings read failure falls back to the checkout's t3.json.
2554+
submodules: yield* projectSettingsFor(input).pipe(
2555+
Effect.map((settings) => settings.worktreeSubmodules),
2556+
Effect.orElseSucceed(() => null),
2557+
),
2558+
},
2559+
);
25512560
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
25522561
yield* maybeRunSetupScript(worktree.worktree.path);
25532562

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2637,11 +2637,14 @@ describe("ProviderCommandReactor", () => {
26372637

26382638
await waitFor(() => harness.startSession.mock.calls.length === 1);
26392639
expect(harness.pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-project" });
2640-
expect(harness.createWorktree).toHaveBeenCalledWith({
2641-
cwd: "/tmp/provider-project",
2642-
refName: "feature/restore",
2643-
path: worktreePath,
2644-
});
2640+
expect(harness.createWorktree).toHaveBeenCalledWith(
2641+
{
2642+
cwd: "/tmp/provider-project",
2643+
refName: "feature/restore",
2644+
path: worktreePath,
2645+
},
2646+
{ submodules: null },
2647+
);
26452648
expect(harness.createWorktree.mock.invocationCallOrder[0]).toBeLessThan(
26462649
harness.startSession.mock.invocationCallOrder[0]!,
26472650
);

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,8 +501,16 @@ const make = Effect.gen(function* () {
501501
});
502502
// A directory deleted without `git worktree remove` leaves an admin entry
503503
// that makes `git worktree add` refuse the path; prune clears it.
504+
// Best effort like the rest of this recovery: a settings read failure
505+
// falls back to the checkout's t3.json.
506+
const submodules = yield* projectSettingsForThread(thread.id).pipe(
507+
Effect.map((settings) => settings.worktreeSubmodules),
508+
Effect.orElseSucceed(() => null),
509+
);
504510
yield* gitWorkflow.pruneWorktrees({ cwd }).pipe(
505-
Effect.andThen(gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath })),
511+
Effect.andThen(
512+
gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath }, { submodules }),
513+
),
506514
Effect.catchCause((cause) =>
507515
Cause.hasInterruptsOnly(cause)
508516
? Effect.failCause(cause)

‎apps/server/src/vcs/GitVcsDriver.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
type VcsRemoveWorktreeInput,
3131
type VcsStatusInput,
3232
type VcsStatusResult,
33+
type WorktreeSubmodules,
3334
} from "@t3tools/contracts";
3435
import {
3536
makeGitVcsDriverCore,
@@ -128,8 +129,10 @@ export interface CreateWorktreeProgress {
128129
total: number;
129130
}) => Effect.Effect<void, never>;
130131
readonly onSubmodulesStarted?: () => Effect.Effect<void, never>;
131-
/** Fires when `.gitmodules` exists but t3.json sets `worktreeSubmodules` to `"none"`. */
132-
readonly onSubmodulesDisabled?: () => Effect.Effect<void, never>;
132+
/** Fires when `.gitmodules` exists but the resolved submodule mode is `"none"`. */
133+
readonly onSubmodulesDisabled?: (input: {
134+
source: "settings" | "t3.json";
135+
}) => Effect.Effect<void, never>;
133136
readonly onSubmoduleLine?: (line: string) => Effect.Effect<void, never>;
134137
readonly onSubmodulesFinished?: (input: {
135138
ok: boolean;
@@ -139,6 +142,12 @@ export interface CreateWorktreeProgress {
139142

140143
export interface CreateWorktreeOptions {
141144
readonly progress?: CreateWorktreeProgress;
145+
/**
146+
* The project-over-environment `worktreeSubmodules` setting. Null (or
147+
* omitted, for callers without settings access) defers to the checkout's
148+
* own t3.json.
149+
*/
150+
readonly submodules?: WorktreeSubmodules | null;
142151
}
143152

144153
export interface GitCommitProgress {

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
GitCommandError,
2727
ReviewDiffPreviewInput,
2828
type ReviewDiffFileContentsInput,
29+
type WorktreeSubmodules,
2930
} from "@t3tools/contracts";
3031
import { ServerConfig } from "../config.ts";
3132
import { gitCommandDuration } from "../observability/Metrics.ts";
@@ -2353,7 +2354,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
23532354
}),
23542355
);
23552356

2356-
it.effect("honors the t3.json worktreeSubmodules setting", () =>
2357+
it.effect("resolves the submodule mode from the option, then t3.json", () =>
23572358
Effect.gen(function* () {
23582359
const fileSystem = yield* FileSystem.FileSystem;
23592360
const pathService = yield* Path.Path;
@@ -2392,17 +2393,22 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
23922393
const worktreesDir = yield* makeTmpDir("git-worktrees-");
23932394

23942395
const createWithMode = Effect.fn(function* (
2395-
fileMode: "recursive" | "top-level" | "none",
2396+
fileMode: WorktreeSubmodules,
23962397
branch: string,
2398+
submodules: WorktreeSubmodules | null = null,
23972399
) {
23982400
yield* writeTextFile(cwd, "t3.json", `{ "worktreeSubmodules": "${fileMode}" }`);
23992401
yield* git(cwd, ["add", "t3.json"]);
2400-
yield* git(cwd, ["commit", "-m", `submodules: ${fileMode}`]);
2402+
// Consecutive cases may reuse a file mode to test the option alone.
2403+
yield* git(cwd, ["commit", "--allow-empty", "-m", `submodules: ${fileMode}`]);
24012404
const worktreePath = pathService.join(worktreesDir, branch);
2402-
const disabled = yield* Ref.make(false);
2405+
const disabled = yield* Ref.make<"settings" | "t3.json" | false>(false);
24032406
yield* driver.createWorktree(
24042407
{ cwd, path: worktreePath, refName: initialBranch, newRefName: branch },
2405-
{ progress: { onSubmodulesDisabled: () => Ref.set(disabled, true) } },
2408+
{
2409+
submodules,
2410+
progress: { onSubmodulesDisabled: ({ source }) => Ref.set(disabled, source) },
2411+
},
24062412
);
24072413
return {
24082414
disabled: yield* Ref.get(disabled),
@@ -2423,8 +2429,19 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
24232429
inner: true,
24242430
nested: false,
24252431
});
2432+
// A resolved setting outranks the file in both directions.
2433+
assert.deepEqual(yield* createWithMode("recursive", "setting-none", "none"), {
2434+
disabled: "settings",
2435+
inner: false,
2436+
nested: false,
2437+
});
2438+
assert.deepEqual(yield* createWithMode("none", "setting-wins", "top-level"), {
2439+
disabled: false,
2440+
inner: true,
2441+
nested: false,
2442+
});
24262443
assert.deepEqual(yield* createWithMode("none", "none"), {
2427-
disabled: true,
2444+
disabled: "t3.json",
24282445
inner: false,
24292446
nested: false,
24302447
});

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
3232
import { compactTraceAttributes } from "@t3tools/shared/observability";
3333
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
3434
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
35+
import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
3536
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
3637
import * as GitVcsDriver from "./GitVcsDriver.ts";
3738
import {
@@ -3095,36 +3096,44 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
30953096
// them. Best-effort: the objects are usually already in the parent's
30963097
// `.git/modules`, but a first-ever clone needs the network, and failing to
30973098
// populate a submodule must not roll back the caller's thread. Repos with
3098-
// hundreds of nested submodules opt out or stop at the top level through
3099-
// t3.json, read from the checkout that was just created.
3099+
// hundreds of nested submodules opt out or stop at the top level; the
3100+
// caller resolves that from settings, or the checkout's t3.json decides.
31003101
const hasSubmodules = yield* fileSystem
31013102
.exists(path.join(worktreePath, ".gitmodules"))
31023103
.pipe(Effect.orElseSucceed(() => false));
3103-
const submoduleMode = hasSubmodules
3104-
? yield* fileSystem.readFileString(path.join(worktreePath, T3_PROJECT_FILE_NAME)).pipe(
3105-
Effect.flatMap((contents) => {
3106-
const file = parseT3ProjectFile(contents);
3107-
return file === null
3108-
? Effect.logWarning("t3.json is invalid; initializing submodules recursively", {
3109-
worktreePath,
3110-
}).pipe(Effect.as("recursive" as const))
3111-
: Effect.succeed(file.worktreeSubmodules ?? "recursive");
3112-
}),
3113-
Effect.orElseSucceed(() => "recursive" as const),
3114-
)
3115-
: "none";
3116-
if (hasSubmodules && submoduleMode === "none" && progress?.onSubmodulesDisabled) {
3117-
yield* progress.onSubmodulesDisabled();
3104+
const submoduleMode = !hasSubmodules
3105+
? { value: "none" as const, source: "environment" as const }
3106+
: resolveProjectFileBackedSetting(
3107+
"worktreeSubmodules",
3108+
options?.submodules ?? null,
3109+
options?.submodules != null
3110+
? null
3111+
: yield* fileSystem.readFileString(path.join(worktreePath, T3_PROJECT_FILE_NAME)).pipe(
3112+
Effect.flatMap((contents) => {
3113+
const file = parseT3ProjectFile(contents);
3114+
return file === null
3115+
? Effect.logWarning("t3.json is invalid; initializing submodules recursively", {
3116+
worktreePath,
3117+
}).pipe(Effect.as(null))
3118+
: Effect.succeed(file);
3119+
}),
3120+
Effect.orElseSucceed(() => null),
3121+
),
3122+
);
3123+
if (hasSubmodules && submoduleMode.value === "none" && progress?.onSubmodulesDisabled) {
3124+
yield* progress.onSubmodulesDisabled({
3125+
source: submoduleMode.source === "t3.json" ? "t3.json" : "settings",
3126+
});
31183127
}
3119-
if (submoduleMode !== "none") {
3128+
if (submoduleMode.value !== "none") {
31203129
if (progress?.onSubmodulesStarted) {
31213130
yield* progress.onSubmodulesStarted();
31223131
}
31233132
const onSubmoduleLine = progress?.onSubmoduleLine;
31243133
yield* runGit(
31253134
"GitVcsDriver.createWorktree.updateSubmodules",
31263135
worktreePath,
3127-
submoduleMode === "recursive"
3136+
submoduleMode.value === "recursive"
31283137
? ["submodule", "update", "--init", "--recursive"]
31293138
: ["submodule", "update", "--init"],
31303139
onSubmoduleLine

‎apps/server/src/ws.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ import {
8181
type WorktreeSetupSnapshot,
8282
} from "@t3tools/contracts";
8383
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
84+
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
8485
import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
8586
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
8687

@@ -1044,6 +1045,35 @@ const makeWsRpcLayer = (
10441045
return output;
10451046
});
10461047

1048+
// Project setting > environment setting; null when neither is set so
1049+
// the driver reads the freshly created checkout's own t3.json (the
1050+
// branch being checked out may declare something the project root does
1051+
// not). Settings that fail to load fall through the same way.
1052+
const resolveBootstrapWorktreeSubmodules = Effect.fnUntraced(function* (input: {
1053+
readonly threadId: ThreadId;
1054+
readonly projectId: ProjectId | null;
1055+
}) {
1056+
const settings = yield* serverSettings.getSettings.pipe(Effect.orElseSucceed(() => null));
1057+
if (!settings) return null;
1058+
// A worktree can also be prepared for an existing thread, whose
1059+
// project is only known through its shell.
1060+
const resolvedProjectId =
1061+
input.projectId ??
1062+
(yield* projectionSnapshotQuery.getThreadShellById(input.threadId).pipe(
1063+
Effect.map((thread) => Option.getOrNull(thread)?.projectId ?? null),
1064+
Effect.orElseSucceed(() => null),
1065+
));
1066+
const project =
1067+
resolvedProjectId === null
1068+
? null
1069+
: yield* projectionSnapshotQuery.getProjectShellById(resolvedProjectId).pipe(
1070+
Effect.map(Option.getOrNull),
1071+
Effect.orElseSucceed(() => null),
1072+
);
1073+
return resolveProjectSettings(settings, resolvedProjectId, project).settings
1074+
.worktreeSubmodules;
1075+
});
1076+
10471077
const dispatchBootstrapTurnStart = (
10481078
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
10491079
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
@@ -1462,6 +1492,10 @@ const makeWsRpcLayer = (
14621492
}
14631493
yield* worktreeSetupTracker.stageStatus(threadId, "checkout", "running");
14641494
let checkoutTotal: number | null = null;
1495+
const submodules = yield* resolveBootstrapWorktreeSubmodules({
1496+
threadId,
1497+
projectId: targetProjectId ?? null,
1498+
});
14651499
const worktree = yield* gitWorkflow.createWorktree(
14661500
{
14671501
cwd: prepareWorktree.projectCwd,
@@ -1471,6 +1505,7 @@ const makeWsRpcLayer = (
14711505
path: null,
14721506
},
14731507
{
1508+
submodules,
14741509
progress: {
14751510
// Git has registered the directory at this point, so a
14761511
// cancel during the submodule step can still remove it.
@@ -1500,12 +1535,12 @@ const makeWsRpcLayer = (
15001535
worktreeSetupTracker.stageStatus(threadId, "submodules", "running"),
15011536
),
15021537
),
1503-
onSubmodulesDisabled: () =>
1538+
onSubmodulesDisabled: ({ source }) =>
15041539
worktreeSetupTracker.stageStatus(
15051540
threadId,
15061541
"submodules",
15071542
"skipped",
1508-
"disabled in t3.json",
1543+
`disabled in ${source}`,
15091544
),
15101545
onSubmoduleLine: (line) => {
15111546
const submodulePath = /Submodule path '([^']+)'/.exec(line)?.[1];

0 commit comments

Comments
 (0)