feat: add configurable source control writing settings (#4204)
Co-authored-by: Claude <[email protected]> Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: codex <[email protected]>
This commit is contained in:
27 files changed
+1335
-125
No files matched your search
@@ -16,11 +16,16 @@ import { expect } from "vite-plus/test";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
ModelSelection,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
GitCommandError,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
TextGenerationError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
@@ -29,6 +34,7 @@ import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceContr
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
|
||||
@@ -65,38 +71,7 @@ function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
generateBranchName: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||
generateThreadTitle: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string }, TextGenerationError>;
|
||||
}
|
||||
type FakeGitTextGeneration = TextGeneration.TextGeneration["Service"];
|
||||
|
||||
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
||||
|
||||
@@ -640,6 +615,7 @@ function preparePullRequestThread(
|
||||
function makeManager(input?: {
|
||||
ghScenario?: FakeGhScenario;
|
||||
textGeneration?: Partial<FakeGitTextGeneration>;
|
||||
serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
|
||||
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
|
||||
}) {
|
||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||
@@ -648,7 +624,7 @@ function makeManager(input?: {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest(input?.serverSettings);
|
||||
|
||||
const vcsDriverLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
@@ -672,6 +648,9 @@ function makeManager(input?: {
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(TextGeneration.TextGeneration, textGeneration),
|
||||
Layer.mock(ProviderRegistry.ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptRunner,
|
||||
input?.setupScriptRunner ?? {
|
||||
@@ -1568,8 +1547,22 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "Use a direct tone.",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Implement stacked git actions", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
@@ -1579,6 +1572,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(generatedPolicy).toMatchObject({ commitInstructions: "Use a direct tone." });
|
||||
expect(result.toast).toMatchObject({
|
||||
description: "Implement stacked git actions",
|
||||
cta: {
|
||||
@@ -1598,6 +1592,118 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves custom style when instructions are empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Preserve custom style", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedPolicy).toEqual({
|
||||
kind: "custom",
|
||||
inferRepositoryConventions: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back when the dedicated source control writer is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
const missingInstanceId = ProviderInstanceId.make("missing_writer");
|
||||
let generatedModelSelection:
|
||||
| TextGeneration.CommitMessageGenerationInput["modelSelection"]
|
||||
| undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
providerInstances: {
|
||||
[missingInstanceId]: {
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection: {
|
||||
instanceId: missingInstanceId,
|
||||
model: "missing-model",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedModelSelection = input.modelSelection;
|
||||
return Effect.succeed({ subject: "Use the available writer", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedModelSelection).toEqual(DEFAULT_SERVER_SETTINGS.textGenerationModelSelection);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves repository conventions style when recent history is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* runGit(repoDir, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(repoDir, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(repoDir, ["config", "user.name", "Test User"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\n");
|
||||
yield* runGit(repoDir, ["add", "README.md"]);
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "repo_conventions" as const,
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Create initial commit", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedPolicy).toEqual({
|
||||
kind: "repo_conventions",
|
||||
commitInstructions:
|
||||
"Follow the repository's established commit message style when examples are available.",
|
||||
changeRequestInstructions:
|
||||
"Follow the repository's established change request title and body style when examples are available.",
|
||||
inferRepositoryConventions: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses custom commit message when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -2535,6 +2641,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(repoDir, ".github", "pull_request_template.md"),
|
||||
"## What changed?\n\n## Verification",
|
||||
);
|
||||
yield* runGit(repoDir, ["add", ".github/pull_request_template.md"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Add pull request template"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
@@ -2543,8 +2656,26 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
|
||||
yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
|
||||
let generatedPolicy: TextGeneration.PrContentGenerationInput["policy"] = undefined;
|
||||
let generatedChangeRequestTemplate: string | undefined;
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "Lead with user impact.",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generatePrContent: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
generatedChangeRequestTemplate = input.changeRequestTemplate;
|
||||
return Effect.succeed({
|
||||
title: "Add stacked git actions",
|
||||
body: "## What changed?\nAdded stacked git actions.",
|
||||
});
|
||||
},
|
||||
},
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
@@ -2569,6 +2700,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(generatedPolicy).toMatchObject({
|
||||
changeRequestInstructions: "Lead with user impact.",
|
||||
});
|
||||
expect(generatedChangeRequestTemplate).toBe("## What changed?\n\n## Verification");
|
||||
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
ModelSelection,
|
||||
type SourceControlWritingStyleSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
@@ -44,12 +45,19 @@ import {
|
||||
|
||||
import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import {
|
||||
conventionalCommitsTextGenerationPolicy,
|
||||
customTextGenerationPolicy,
|
||||
repositoryConventionsTextGenerationPolicy,
|
||||
} from "../textGeneration/TextGenerationPresets.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { detectPrTemplate } from "../sourceControl/PrTemplateDetection.ts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
@@ -61,6 +69,11 @@ export interface GitRunStackedActionOptions {
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
interface SourceControlTextGenerationSettings {
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly style: SourceControlWritingStyleSettings;
|
||||
}
|
||||
|
||||
export class GitManager extends Context.Service<
|
||||
GitManager,
|
||||
{
|
||||
@@ -565,11 +578,58 @@ export const make = Effect.gen(function* () {
|
||||
const gitCore = yield* GitVcsDriver.GitVcsDriver;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
||||
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
|
||||
|
||||
const readRecentCommitSubjects = (cwd: string) =>
|
||||
gitCore
|
||||
.execute({
|
||||
operation: "GitManager.readRecentCommitSubjects",
|
||||
cwd,
|
||||
args: ["log", "-n", "20", "--no-merges", "--pretty=format:%s"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) =>
|
||||
result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
Effect.orElseSucceed(() => []),
|
||||
);
|
||||
|
||||
const resolveStylePolicy = (cwd: string, style: SourceControlWritingStyleSettings) =>
|
||||
Effect.gen(function* () {
|
||||
switch (style.mode) {
|
||||
case "conventional_commits":
|
||||
return conventionalCommitsTextGenerationPolicy;
|
||||
case "custom":
|
||||
return customTextGenerationPolicy(
|
||||
style.customInstructions
|
||||
? {
|
||||
commitInstructions: style.customInstructions,
|
||||
changeRequestInstructions: style.customInstructions,
|
||||
}
|
||||
: {},
|
||||
);
|
||||
case "repo_conventions": {
|
||||
const subjects = yield* readRecentCommitSubjects(cwd);
|
||||
if (subjects.length === 0) {
|
||||
return repositoryConventionsTextGenerationPolicy;
|
||||
}
|
||||
const examples = ["Recent commit subjects from this repository:", ...subjects].join("\n");
|
||||
return {
|
||||
...repositoryConventionsTextGenerationPolicy,
|
||||
commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
|
||||
changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
const randomUUIDv4 = (cwd: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
@@ -1330,7 +1390,7 @@ export const make = Effect.gen(function* () {
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
modelSelection: ModelSelection;
|
||||
settings: SourceControlTextGenerationSettings;
|
||||
}) {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
if (!context) {
|
||||
@@ -1349,6 +1409,8 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
|
||||
const policy = yield* resolveStylePolicy(input.cwd, input.settings.style);
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
@@ -1356,7 +1418,8 @@ export const make = Effect.gen(function* () {
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
modelSelection: input.modelSelection,
|
||||
...(policy ? { policy } : {}),
|
||||
modelSelection: input.settings.modelSelection,
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
@@ -1370,7 +1433,7 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const runCommitStep = Effect.fn("runCommitStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
action: "commit" | "commit_push" | "commit_push_pr",
|
||||
branch: string | null,
|
||||
@@ -1405,7 +1468,7 @@ export const make = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
modelSelection,
|
||||
settings,
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
@@ -1483,7 +1546,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runPrStep = Effect.fn("runPrStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
emit: GitActionProgressEmitter,
|
||||
@@ -1532,6 +1595,11 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseBranch);
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
|
||||
const policy = yield* resolveStylePolicy(cwd, settings.style);
|
||||
const changeRequestTemplate =
|
||||
settings.style.followChangeRequestTemplates && provider.kind === "github"
|
||||
? Option.getOrUndefined(yield* detectPrTemplate(cwd, baseRangeRef, gitCore.execute))
|
||||
: undefined;
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd,
|
||||
@@ -1540,7 +1608,9 @@ export const make = Effect.gen(function* () {
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
modelSelection,
|
||||
...(changeRequestTemplate ? { changeRequestTemplate } : {}),
|
||||
...(policy ? { policy } : {}),
|
||||
modelSelection: settings.modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(
|
||||
@@ -1820,7 +1890,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
@@ -1832,7 +1902,7 @@ export const make = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
modelSelection,
|
||||
settings,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -1921,8 +1991,23 @@ export const make = Effect.gen(function* () {
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
const modelSelection = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.textGenerationModelSelection),
|
||||
const textGenerationSettings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
settings.sourceControlWriterModelSelection === null
|
||||
? Effect.succeed({
|
||||
modelSelection: settings.textGenerationModelSelection,
|
||||
style: settings.sourceControlWritingStyle,
|
||||
})
|
||||
: providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) => ({
|
||||
modelSelection: ServerSettings.resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
providers,
|
||||
),
|
||||
style: settings.sourceControlWritingStyle,
|
||||
})),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitManagerError({
|
||||
@@ -1942,7 +2027,7 @@ export const make = Effect.gen(function* () {
|
||||
label: "Preparing feature branch...",
|
||||
});
|
||||
const result = yield* runFeatureBranchStep(
|
||||
modelSelection,
|
||||
textGenerationSettings,
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
@@ -1968,7 +2053,7 @@ export const make = Effect.gen(function* () {
|
||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||
Effect.flatMap(() =>
|
||||
runCommitStep(
|
||||
modelSelection,
|
||||
textGenerationSettings,
|
||||
input.cwd,
|
||||
commitAction,
|
||||
currentBranch,
|
||||
@@ -2005,7 +2090,7 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||
Effect.flatMap(() =>
|
||||
runPrStep(modelSelection, input.cwd, currentBranch, progress.emit),
|
||||
runPrStep(textGenerationSettings, input.cwd, currentBranch, progress.emit),
|
||||
),
|
||||
)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
@@ -38,7 +38,10 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
resolveSourceControlWriterModelSelection,
|
||||
ServerSettingsService,
|
||||
} from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
|
||||
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
|
||||
@@ -688,8 +691,14 @@ const make = Effect.gen(function* () {
|
||||
const cwd = input.worktreePath;
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
const settings = yield* serverSettingsService.getSettings;
|
||||
const modelSelection =
|
||||
settings.sourceControlWriterModelSelection === null
|
||||
? settings.textGenerationModelSelection
|
||||
: resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
yield* providerRegistry.getProviders,
|
||||
);
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd,
|
||||
|
||||
@@ -325,6 +325,73 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"preserves the source control writer selection when its provider instance is disabled",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const instanceId = ProviderInstanceId.make("codex_writer");
|
||||
const sourceControlWriterModelSelection = {
|
||||
instanceId,
|
||||
model: "gpt-5.4-mini",
|
||||
};
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
});
|
||||
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: false,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(next.sourceControlWriterModelSelection, sourceControlWriterModelSelection);
|
||||
assert.deepEqual(
|
||||
ServerSettingsModule.resolveSourceControlWriterModelSelection(next),
|
||||
next.textGenerationModelSelection,
|
||||
);
|
||||
assert.deepEqual(
|
||||
(yield* serverSettings.getSettings).sourceControlWriterModelSelection,
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.deepEqual(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.parse(raw).sourceControlWriterModelSelection,
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
|
||||
const restored = yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
ServerSettingsModule.resolveSourceControlWriterModelSelection(restored),
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("drops stale text generation options when resetting model selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
|
||||
@@ -11,11 +11,10 @@
|
||||
* @module ServerSettings
|
||||
*/
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
isProviderDriverKind,
|
||||
type ModelSelection,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceEnvironmentVariable,
|
||||
@@ -47,9 +46,14 @@ import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
import {
|
||||
applyServerSettingsPatch,
|
||||
isModelSelectionProviderEnabled,
|
||||
} from "@t3tools/shared/serverSettings";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
|
||||
export { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
|
||||
|
||||
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
|
||||
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
|
||||
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
|
||||
@@ -148,12 +152,13 @@ const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
getSettings: Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
|
||||
Effect.flatMap(normalizeServerSettings),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
Effect.map(resolveTextGenerationProvider),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsService["Service"];
|
||||
@@ -165,35 +170,10 @@ export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
const getLegacyProviderSettings = (
|
||||
settings: ServerSettings,
|
||||
provider: ProviderDriverKind,
|
||||
): LegacyProviderSettings | undefined =>
|
||||
(settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
|
||||
|
||||
/**
|
||||
* Ensure the `textGenerationModelSelection` points to an enabled provider.
|
||||
* If the selected provider is disabled, fall back to the first enabled
|
||||
* provider with its default model. This is applied at read-time so the
|
||||
* persisted preference is preserved for when a provider is re-enabled.
|
||||
*/
|
||||
function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
const selection = settings.textGenerationModelSelection;
|
||||
const instanceConfig = settings.providerInstances[selection.instanceId];
|
||||
if (instanceConfig !== undefined) {
|
||||
return (instanceConfig.enabled ?? true) ? settings : fallbackTextGenerationProvider(settings);
|
||||
}
|
||||
|
||||
if (
|
||||
isProviderDriverKind(selection.instanceId) &&
|
||||
getLegacyProviderSettings(settings, selection.instanceId)?.enabled
|
||||
) {
|
||||
return settings;
|
||||
}
|
||||
|
||||
return fallbackTextGenerationProvider(settings);
|
||||
return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)
|
||||
? settings
|
||||
: fallbackTextGenerationProvider(settings);
|
||||
}
|
||||
|
||||
function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
@@ -208,9 +188,9 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
textGenerationModelSelection: {
|
||||
instanceId: ProviderInstanceId.make(fallback),
|
||||
model:
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
} satisfies ModelSelection,
|
||||
};
|
||||
}
|
||||
@@ -218,6 +198,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
|
||||
"automaticGitFetchInterval",
|
||||
"sourceControlWriterModelSelection",
|
||||
"textGenerationModelSelection",
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { detectPrTemplate } from "./PrTemplateDetection.ts";
|
||||
|
||||
const SINGLE_TEMPLATE_PATHS = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"pull_request_template.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
"docs/PULL_REQUEST_TEMPLATE.md",
|
||||
] as const;
|
||||
|
||||
const TEMPLATE_DIRECTORIES = [
|
||||
".github/PULL_REQUEST_TEMPLATE",
|
||||
"PULL_REQUEST_TEMPLATE",
|
||||
"docs/PULL_REQUEST_TEMPLATE",
|
||||
] as const;
|
||||
|
||||
const PrTemplateDetectionTestLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-pr-template-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* git.execute({
|
||||
operation: "PrTemplateDetection.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
});
|
||||
});
|
||||
|
||||
const runWithTempDirectory = <A, E, R>(
|
||||
test: (cwd: string) => Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
|
||||
) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-pr-template-" });
|
||||
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
return yield* test(cwd);
|
||||
}),
|
||||
).pipe(Effect.provide(PrTemplateDetectionTestLayer));
|
||||
|
||||
const writeTemplate = (cwd: string, relativePath: string, contents: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const templatePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(templatePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(templatePath, contents);
|
||||
return templatePath;
|
||||
});
|
||||
|
||||
const commitTemplates = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["add", "-A"]);
|
||||
yield* runGit(cwd, ["commit", "--allow-empty", "-m", "Add pull request templates"]);
|
||||
});
|
||||
|
||||
const detectTemplate = (cwd: string, treeish = "HEAD") =>
|
||||
Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* detectPrTemplate(cwd, treeish, git.execute);
|
||||
});
|
||||
|
||||
it.effect.each(SINGLE_TEMPLATE_PATHS)("recognizes $0", (relativePath) =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, relativePath, `template from ${relativePath}`);
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), `template from ${relativePath}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads templates from the requested base tree", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, "README.md", "initial\n");
|
||||
yield* commitTemplates(cwd);
|
||||
yield* runGit(cwd, ["branch", "feature"]);
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", "base template");
|
||||
yield* commitTemplates(cwd);
|
||||
yield* runGit(cwd, ["checkout", "feature"]);
|
||||
|
||||
assert.isTrue(Option.isNone(yield* detectTemplate(cwd)));
|
||||
assert.strictEqual(
|
||||
Option.getOrUndefined(yield* detectTemplate(cwd, "main")),
|
||||
"base template",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses the first non-empty template in the configured path order", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", " \n");
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE.md", " ## Preferred template \n");
|
||||
yield* writeTemplate(cwd, "pull_request_template.md", "## Later template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "## Preferred template");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.each(TEMPLATE_DIRECTORIES)("recognizes the $0 directory", (relativeDirectory) =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, `${relativeDirectory}/template.MD`, "directory template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "directory template");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("skips unusable directory entries and uses the one valid template", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const templateDirectory = path.join(cwd, ".github", "PULL_REQUEST_TEMPLATE");
|
||||
yield* fileSystem.makeDirectory(path.join(templateDirectory, "b-directory.md"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(templateDirectory, "a-empty.md"), " \n");
|
||||
yield* fileSystem.symlink(
|
||||
path.join(templateDirectory, "missing.md"),
|
||||
path.join(templateDirectory, "c-broken.md"),
|
||||
);
|
||||
yield* fileSystem.writeFileString(path.join(templateDirectory, "z-valid.md"), "valid");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "valid");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not guess between multiple directory templates", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE/a.md", "first");
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE/b.md", "second");
|
||||
yield* writeTemplate(cwd, "PULL_REQUEST_TEMPLATE/fallback.md", "fallback");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.isTrue(Option.isNone(template));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects a committed template symlink escaping the repository", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const outsideDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-pr-template-outside-",
|
||||
});
|
||||
const outsideTemplate = path.join(outsideDirectory, "secret.md");
|
||||
yield* fileSystem.writeFileString(outsideTemplate, "LOCAL_SECRET_SENTINEL");
|
||||
const escapedTemplatePath = path.join(cwd, ".github", "pull_request_template.md");
|
||||
yield* fileSystem.makeDirectory(path.dirname(escapedTemplatePath), { recursive: true });
|
||||
yield* fileSystem.symlink(outsideTemplate, escapedTemplatePath);
|
||||
yield* writeTemplate(cwd, "pull_request_template.md", "safe template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "safe template");
|
||||
assert.notInclude(
|
||||
Option.getOrElse(template, () => ""),
|
||||
"LOCAL_SECRET_SENTINEL",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads the committed template when a worktree parent is replaced", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const outsideDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-pr-template-outside-",
|
||||
});
|
||||
const templatePath = yield* writeTemplate(
|
||||
cwd,
|
||||
".github/pull_request_template.md",
|
||||
"committed template",
|
||||
);
|
||||
yield* commitTemplates(cwd);
|
||||
yield* writeTemplate(outsideDirectory, "pull_request_template.md", "LOCAL_SECRET_SENTINEL");
|
||||
|
||||
const templateDirectory = path.dirname(templatePath);
|
||||
yield* fileSystem.rename(templateDirectory, path.join(cwd, ".github-original"));
|
||||
yield* fileSystem.symlink(outsideDirectory, templateDirectory);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "committed template");
|
||||
assert.notInclude(
|
||||
Option.getOrElse(template, () => ""),
|
||||
"LOCAL_SECRET_SENTINEL",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds template reads and marks truncated content", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const prefix = "a".repeat(8_000);
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", `${prefix}SECRET_SENTINEL`);
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = Option.getOrThrow(yield* detectTemplate(cwd));
|
||||
assert.strictEqual(template, `${prefix}\n\n[truncated]`);
|
||||
assert.lengthOf(template.match(/\[truncated\]/g) ?? [], 1);
|
||||
assert.notInclude(template, "SECRET_SENTINEL");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { GitCommandError } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
|
||||
const TEMPLATE_MAX_BYTES = 8_000;
|
||||
const TREE_LIST_MAX_BYTES = 100_000;
|
||||
const TRUNCATION_MARKER = "[truncated]";
|
||||
|
||||
const TEMPLATE_PATHS = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"pull_request_template.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
"docs/PULL_REQUEST_TEMPLATE.md",
|
||||
] as const;
|
||||
|
||||
const TEMPLATE_DIRECTORIES = [
|
||||
".github/PULL_REQUEST_TEMPLATE",
|
||||
"PULL_REQUEST_TEMPLATE",
|
||||
"docs/PULL_REQUEST_TEMPLATE",
|
||||
] as const;
|
||||
|
||||
const TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;
|
||||
|
||||
type ExecuteGit = GitVcsDriver.GitVcsDriver["Service"]["execute"];
|
||||
|
||||
interface TemplateTreeEntry {
|
||||
readonly objectId: string;
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
function parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {
|
||||
const entries: TemplateTreeEntry[] = [];
|
||||
for (const record of output.split("\0")) {
|
||||
if (record.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = record.indexOf("\t");
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [mode, type, objectId] = record.slice(0, separator).split(" ");
|
||||
if (
|
||||
type !== "blob" ||
|
||||
(mode !== "100644" && mode !== "100755") ||
|
||||
!objectId ||
|
||||
!/^[0-9a-f]{40,64}$/.test(objectId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
entries.push({ objectId, path: record.slice(separator + 1) });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function readTemplateBlob(input: {
|
||||
readonly cwd: string;
|
||||
readonly executeGit: ExecuteGit;
|
||||
readonly entry: TemplateTreeEntry;
|
||||
}): Effect.Effect<Option.Option<string>, GitCommandError> {
|
||||
return input
|
||||
.executeGit({
|
||||
operation: "PrTemplateDetection.readTemplateBlob",
|
||||
cwd: input.cwd,
|
||||
args: ["cat-file", "blob", input.entry.objectId],
|
||||
maxOutputBytes: TEMPLATE_MAX_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
const template = result.stdout.trim();
|
||||
if (template.length === 0) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some(
|
||||
result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
|
||||
? `${template}\n\n${TRUNCATION_MARKER}`
|
||||
: template,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type DirectoryTemplateResult =
|
||||
| { readonly _tag: "None" }
|
||||
| { readonly _tag: "Ambiguous" }
|
||||
| { readonly _tag: "Template"; readonly template: string };
|
||||
|
||||
function readTemplateDirectory(input: {
|
||||
readonly cwd: string;
|
||||
readonly executeGit: ExecuteGit;
|
||||
readonly entries: ReadonlyArray<TemplateTreeEntry>;
|
||||
readonly directory: string;
|
||||
}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {
|
||||
return Effect.gen(function* () {
|
||||
const prefix = `${input.directory}/`;
|
||||
const candidates = input.entries.filter((entry) => {
|
||||
if (!entry.path.startsWith(prefix)) {
|
||||
return false;
|
||||
}
|
||||
const relativePath = entry.path.slice(prefix.length);
|
||||
return !relativePath.includes("/") && relativePath.toLowerCase().endsWith(".md");
|
||||
});
|
||||
|
||||
const templates: string[] = [];
|
||||
for (const entry of candidates) {
|
||||
const template = yield* readTemplateBlob({ ...input, entry });
|
||||
if (Option.isSome(template)) {
|
||||
templates.push(template.value);
|
||||
if (templates.length > 1) {
|
||||
return { _tag: "Ambiguous" } as const;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return templates[0]
|
||||
? ({ _tag: "Template", template: templates[0] } as const)
|
||||
: ({ _tag: "None" } as const);
|
||||
});
|
||||
}
|
||||
|
||||
export const detectPrTemplate = Effect.fn("detectPrTemplate")(function* (
|
||||
cwd: string,
|
||||
treeish: string,
|
||||
executeGit: ExecuteGit,
|
||||
) {
|
||||
return yield* Effect.gen(function* () {
|
||||
// Worktree paths can be replaced between validation and open. Read regular blobs from the
|
||||
// committed base tree so repository-controlled symlinks and path races never reach the host filesystem.
|
||||
const result = yield* executeGit({
|
||||
operation: "PrTemplateDetection.listTemplates",
|
||||
cwd,
|
||||
args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
|
||||
maxOutputBytes: TREE_LIST_MAX_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
});
|
||||
if (result.stdoutTruncated) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const entries = parseTemplateTreeEntries(result.stdout);
|
||||
const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
|
||||
for (const templatePath of TEMPLATE_PATHS) {
|
||||
const entry = entriesByPath.get(templatePath);
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
const template = yield* readTemplateBlob({ cwd, executeGit, entry });
|
||||
if (Option.isSome(template)) {
|
||||
return template;
|
||||
}
|
||||
}
|
||||
|
||||
for (const directory of TEMPLATE_DIRECTORIES) {
|
||||
const directoryTemplate = yield* readTemplateDirectory({
|
||||
cwd,
|
||||
executeGit,
|
||||
entries,
|
||||
directory,
|
||||
});
|
||||
if (directoryTemplate._tag === "Template") {
|
||||
return Option.some(directoryTemplate.template);
|
||||
}
|
||||
if (directoryTemplate._tag === "Ambiguous") {
|
||||
return Option.none();
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
}).pipe(Effect.orElseSucceed(() => Option.none()));
|
||||
});
|
||||
@@ -272,6 +272,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
@@ -299,6 +300,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
|
||||
@@ -305,6 +305,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
@@ -332,6 +333,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
|
||||
@@ -172,6 +172,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
@@ -199,6 +200,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
|
||||
@@ -164,6 +164,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
@@ -191,6 +192,8 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
|
||||
@@ -530,6 +530,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateCommitMessage",
|
||||
@@ -556,6 +557,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generatePrContent",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
|
||||
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
|
||||
|
||||
@@ -16,6 +17,7 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
@@ -34,6 +36,8 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
changeRequestTemplate?: string | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
@@ -77,7 +81,7 @@ export interface TextGenerationService {
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
* TextGeneration - Service tag for commit and change request text generation.
|
||||
*/
|
||||
export class TextGeneration extends Context.Service<
|
||||
TextGeneration,
|
||||
@@ -90,7 +94,7 @@ export class TextGeneration extends Context.Service<
|
||||
) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Generate pull request title/body from branch and diff context.
|
||||
* Generate change request title/body from branch and diff context.
|
||||
*/
|
||||
readonly generatePrContent: (
|
||||
input: PrContentGenerationInput,
|
||||
|
||||
@@ -49,6 +49,23 @@ describe("buildCommitMessagePrompt", () => {
|
||||
|
||||
expect(result.prompt).toContain("Branch: (detached)");
|
||||
});
|
||||
|
||||
it("includes policy instructions", () => {
|
||||
const result = buildCommitMessagePrompt({
|
||||
branch: "main",
|
||||
stagedSummary: "M a.ts",
|
||||
stagedPatch: "diff",
|
||||
includeBranch: false,
|
||||
policy: {
|
||||
kind: "custom",
|
||||
commitInstructions: "Use a terse repository-specific subject.",
|
||||
inferRepositoryConventions: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Additional instructions:");
|
||||
expect(result.prompt).toContain("Use a terse repository-specific subject.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPrContentPrompt", () => {
|
||||
@@ -69,6 +86,30 @@ describe("buildPrContentPrompt", () => {
|
||||
expect(result.prompt).toContain("3 files changed");
|
||||
expect(result.prompt).toContain("Diff patch:");
|
||||
expect(result.prompt).toContain("export function login()");
|
||||
expect(result.prompt).toContain("include headings '## Summary' and '## Testing'");
|
||||
});
|
||||
|
||||
it("follows a repository PR template instead of the default body headings", () => {
|
||||
const result = buildPrContentPrompt({
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/auth",
|
||||
commitSummary: "feat: add login page",
|
||||
diffSummary: "3 files changed",
|
||||
diffPatch: "diff",
|
||||
changeRequestTemplate: "<!-- remove me -->\n## What changed\n\n## Verification",
|
||||
policy: {
|
||||
kind: "custom",
|
||||
changeRequestInstructions: "Keep the title in sentence case.",
|
||||
inferRepositoryConventions: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Keep the title in sentence case.");
|
||||
expect(result.prompt).toContain("follow the repository change request template structure");
|
||||
expect(result.prompt).toContain("drop HTML comments from the template");
|
||||
expect(result.prompt).toContain("Repository change request template:");
|
||||
expect(result.prompt).toContain("<!-- remove me -->\n## What changed\n\n## Verification");
|
||||
expect(result.prompt).not.toContain("include headings '## Summary' and '## Testing'");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -25,12 +25,12 @@ export interface CommitMessagePromptInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch: boolean;
|
||||
includeBranch?: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
const wantsBranch = input.includeBranch;
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
@@ -76,7 +76,7 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR content
|
||||
// Change request content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PrContentPromptInput {
|
||||
@@ -85,19 +85,34 @@ export interface PrContentPromptInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
changeRequestTemplate?: string | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
const changeRequestTemplate = input.changeRequestTemplate?.trim();
|
||||
const bodyRules = changeRequestTemplate
|
||||
? [
|
||||
"- body must be markdown and follow the repository change request template structure",
|
||||
"- fill in the template sections appropriately for this change",
|
||||
"- drop HTML comments from the template in the generated body",
|
||||
"- keep the template's markdown structure",
|
||||
]
|
||||
: [
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
];
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"You write source control change request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
...bodyRules,
|
||||
...policyInstruction(input.policy?.changeRequestInstructions),
|
||||
...(changeRequestTemplate
|
||||
? ["", "Repository change request template:", limitSection(changeRequestTemplate, 8_000)]
|
||||
: []),
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
|
||||
@@ -39,6 +39,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
open?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
triggerAriaLabel?: string;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
|
||||
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
|
||||
@@ -146,6 +147,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
aria-label={props.triggerAriaLabel}
|
||||
size="sm"
|
||||
variant={props.triggerVariant ?? "ghost"}
|
||||
data-chat-provider-model-picker="true"
|
||||
|
||||
@@ -392,7 +392,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
@@ -445,10 +445,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(isGitWritingModelDirty ? ["Git writing model"] : []),
|
||||
...(isTextGenerationModelDirty ? ["Text generation model"] : []),
|
||||
],
|
||||
[
|
||||
isGitWritingModelDirty,
|
||||
isTextGenerationModelDirty,
|
||||
settings.autoOpenPlanSidebar,
|
||||
settings.confirmThreadArchive,
|
||||
settings.confirmThreadDelete,
|
||||
@@ -533,21 +533,21 @@ export function GeneralSettingsPanel() {
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const gitModelInstanceEntries = sortProviderInstanceEntries(
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = gitModelInstanceEntries.find(
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const gitModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
@@ -1000,9 +1000,9 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Text generation model"
|
||||
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
description="Default model for generated text like thread titles and source control content. Source control settings can override it with a dedicated source control writer model."
|
||||
resetAction={
|
||||
isGitWritingModelDirty ? (
|
||||
isTextGenerationModelDirty ? (
|
||||
<SettingResetButton
|
||||
label="text generation model"
|
||||
onClick={() =>
|
||||
@@ -1020,8 +1020,8 @@ export function GeneralSettingsPanel() {
|
||||
activeInstanceId={textGenInstanceId}
|
||||
model={textGenModel}
|
||||
lockedProvider={null}
|
||||
instanceEntries={gitModelInstanceEntries}
|
||||
modelOptionsByInstance={gitModelOptionsByInstance}
|
||||
instanceEntries={textGenerationModelInstanceEntries}
|
||||
modelOptionsByInstance={textGenerationModelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
type Icon,
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
|
||||
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
@@ -195,7 +196,7 @@ function itemSummary({
|
||||
<span>
|
||||
{item.label} is not authenticated on this server. Sign in or configure credentials using
|
||||
the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
|
||||
tool on the server host to enable pull request features.
|
||||
tool on the server host to enable change request features.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -513,6 +514,8 @@ export function SourceControlSettingsPanel() {
|
||||
onScan={handleScan}
|
||||
/>
|
||||
)}
|
||||
|
||||
{environmentId !== null ? <SourceControlWritingSettingsSection /> : null}
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useRef } from "react";
|
||||
import type { SourceControlWritingStyleMode } from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../../providerInstances";
|
||||
import {
|
||||
getCustomModelOptionsByInstance,
|
||||
resolveAppModelSelectionState,
|
||||
} from "../../modelSelection";
|
||||
import { primaryServerProvidersAtom } from "../../state/server";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Textarea } from "../ui/textarea";
|
||||
import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; description: string }> =
|
||||
{
|
||||
repo_conventions: {
|
||||
label: "Repository conventions",
|
||||
description: "In each project, matches recent change descriptions and change request titles.",
|
||||
},
|
||||
conventional_commits: {
|
||||
label: "Conventional Commits",
|
||||
description:
|
||||
"Uses Conventional Commit prefixes for change descriptions; change request titles and descriptions stay concise.",
|
||||
},
|
||||
custom: {
|
||||
label: "Custom instructions",
|
||||
description:
|
||||
"Applies your instructions to change descriptions and change request titles and descriptions in every project.",
|
||||
},
|
||||
};
|
||||
|
||||
export function SourceControlWritingSettingsSection() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
|
||||
const style = settings.sourceControlWritingStyle;
|
||||
const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
|
||||
const isSourceControlWritingStyleDirty =
|
||||
style.mode !== defaults.mode || style.customInstructions !== defaults.customInstructions;
|
||||
|
||||
const defaultModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const usesDedicatedModel = settings.sourceControlWriterModelSelection !== null;
|
||||
const resolvedSourceControlWriterSelection = resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
serverProviders,
|
||||
);
|
||||
const activeSelection =
|
||||
resolvedSourceControlWriterSelection === settings.textGenerationModelSelection
|
||||
? defaultModelSelection
|
||||
: resolvedSourceControlWriterSelection;
|
||||
const instanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const modelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
activeSelection.instanceId,
|
||||
activeSelection.model,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="Text generation">
|
||||
<SettingsRow
|
||||
title="Source control writing style"
|
||||
description={MODE_OPTIONS[style.mode].description}
|
||||
resetAction={
|
||||
isSourceControlWritingStyleDirty ? (
|
||||
<SettingResetButton
|
||||
label="source control writing style"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
mode: defaults.mode,
|
||||
customInstructions: defaults.customInstructions,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={style.mode}
|
||||
onValueChange={(value) => {
|
||||
const customInstructions = customInstructionsRef.current?.value.trim();
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
mode: value as SourceControlWritingStyleMode,
|
||||
...(customInstructions !== undefined ? { customInstructions } : {}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-56" aria-label="Source control writing style">
|
||||
<SelectValue>{MODE_OPTIONS[style.mode].label}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
|
||||
<SelectItem key={mode} hideIndicator value={mode}>
|
||||
{MODE_OPTIONS[mode].label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
>
|
||||
{style.mode === "custom" ? (
|
||||
<div className="mt-3 max-w-2xl pb-3.5">
|
||||
<Textarea
|
||||
key={style.customInstructions}
|
||||
ref={customInstructionsRef}
|
||||
defaultValue={style.customInstructions}
|
||||
onBlur={(event) => {
|
||||
const customInstructions = event.target.value.trim();
|
||||
if (customInstructions !== style.customInstructions) {
|
||||
updateSettings({ sourceControlWritingStyle: { customInstructions } });
|
||||
}
|
||||
}}
|
||||
rows={4}
|
||||
placeholder="Keep titles concise. Use short bullet points in descriptions."
|
||||
aria-label="Custom source control writing instructions"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
title="Follow change request templates"
|
||||
description="Structures change request descriptions using the current repository's template when one is available."
|
||||
resetAction={
|
||||
style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
|
||||
<SettingResetButton
|
||||
label="change request templates"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
followChangeRequestTemplates: defaults.followChangeRequestTemplates,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={style.followChangeRequestTemplates}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
followChangeRequestTemplates: Boolean(checked),
|
||||
},
|
||||
})
|
||||
}
|
||||
aria-label="Follow change request templates"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Source control writer model"
|
||||
description="Optional model override for change descriptions, change request titles and descriptions, and branch or bookmark names. Off uses the global text generation model."
|
||||
control={
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{usesDedicatedModel ? (
|
||||
<ProviderModelPicker
|
||||
activeInstanceId={activeSelection.instanceId}
|
||||
model={activeSelection.model}
|
||||
lockedProvider={null}
|
||||
instanceEntries={instanceEntries}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
triggerAriaLabel="Source control writer model"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
updateSettings({
|
||||
sourceControlWriterModelSelection: createModelSelection(instanceId, model),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<Switch
|
||||
checked={usesDedicatedModel}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sourceControlWriterModelSelection: checked
|
||||
? createModelSelection(
|
||||
defaultModelSelection.instanceId,
|
||||
defaultModelSelection.model,
|
||||
defaultModelSelection.options,
|
||||
)
|
||||
: null,
|
||||
})
|
||||
}
|
||||
aria-label="Use a separate source control writer model"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -32,6 +32,8 @@ import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
|
||||
|
||||
const clientSettingsListeners = new Set<() => void>();
|
||||
const clientSettingsHydrationListeners = new Set<() => void>();
|
||||
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
@@ -144,7 +146,7 @@ function persistClientSettings(settings: ClientSettings): void {
|
||||
|
||||
const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
|
||||
|
||||
function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
function splitPatch(patch: UnifiedSettingsPatch): {
|
||||
serverPatch: ServerSettingsPatch;
|
||||
clientPatch: ClientSettingsPatch;
|
||||
} {
|
||||
@@ -246,7 +248,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
|
||||
"server settings update",
|
||||
);
|
||||
const updateSettings = useCallback(
|
||||
(patch: Partial<UnifiedSettings>) => {
|
||||
(patch: UnifiedSettingsPatch) => {
|
||||
const { serverPatch, clientPatch } = splitPatch(patch);
|
||||
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
defaultInstanceIdForDriver,
|
||||
type ModelSelection,
|
||||
ProviderDriverKind,
|
||||
@@ -281,7 +281,7 @@ export function resolveAppModelSelectionState(
|
||||
): ModelSelection {
|
||||
const selection = settings.textGenerationModelSelection ?? {
|
||||
instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
model: DEFAULT_TEXT_GENERATION_MODEL,
|
||||
};
|
||||
const entries = deriveProviderInstanceEntries(providers);
|
||||
const selectedEntry = entries.find(
|
||||
@@ -296,7 +296,7 @@ export function resolveAppModelSelectionState(
|
||||
const model =
|
||||
resolveAppModelSelectionForInstance(entry.instanceId, settings, providers, selectedModel) ??
|
||||
entry.models[0]?.slug ??
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
|
||||
if (!model) {
|
||||
return createModelSelection(entry.instanceId, "", []);
|
||||
}
|
||||
|
||||
@@ -52,6 +52,12 @@ function SettingsContentLayout() {
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
|
||||
const activeElement = document.activeElement;
|
||||
if (activeElement instanceof HTMLElement) {
|
||||
activeElement.blur();
|
||||
}
|
||||
|
||||
navigateBackWithinApp();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -144,7 +144,7 @@ export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
];
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
|
||||
export const DEFAULT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
|
||||
@@ -155,10 +155,10 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
|
||||
};
|
||||
|
||||
/** Per-provider text generation model defaults. */
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
|
||||
export const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<
|
||||
Record<ProviderDriverKind, string>
|
||||
> = {
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
[CODEX_DRIVER_KIND]: DEFAULT_TEXT_GENERATION_MODEL,
|
||||
[CLAUDE_DRIVER_KIND]: "claude-haiku-4-5",
|
||||
[CURSOR_DRIVER_KIND]: "composer-2",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
|
||||
@@ -136,6 +136,33 @@ describe("ServerSettings worktree defaults", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettings.sourceControlWritingStyle", () => {
|
||||
it("defaults all style settings for legacy configs", () => {
|
||||
const settings = decodeServerSettings({});
|
||||
|
||||
expect(settings.sourceControlWritingStyle).toEqual({
|
||||
mode: "repo_conventions",
|
||||
customInstructions: "",
|
||||
followChangeRequestTemplates: true,
|
||||
});
|
||||
expect(settings.sourceControlWriterModelSelection).toBeNull();
|
||||
});
|
||||
|
||||
it("trims partial style updates", () => {
|
||||
const patch = decodeServerSettingsPatch({
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom",
|
||||
customInstructions: " Prefer concise wording. ",
|
||||
},
|
||||
});
|
||||
|
||||
expect(patch.sourceControlWritingStyle).toEqual({
|
||||
mode: "custom",
|
||||
customInstructions: "Prefer concise wording.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettingsPatch.providerInstances", () => {
|
||||
it("treats providerInstances as an optional whole-map replacement", () => {
|
||||
const patch = decodeServerSettingsPatch({});
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
|
||||
import { DEFAULT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
|
||||
import { ModelSelection } from "./orchestration.ts";
|
||||
import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
@@ -395,6 +395,24 @@ export const ObservabilitySettings = Schema.Struct({
|
||||
});
|
||||
export type ObservabilitySettings = typeof ObservabilitySettings.Type;
|
||||
|
||||
export const SourceControlWritingStyleMode = Schema.Literals([
|
||||
"repo_conventions",
|
||||
"conventional_commits",
|
||||
"custom",
|
||||
]);
|
||||
export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
|
||||
|
||||
export const SourceControlWritingStyleSettings = Schema.Struct({
|
||||
mode: SourceControlWritingStyleMode.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
|
||||
),
|
||||
customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
followChangeRequestTemplates: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
),
|
||||
});
|
||||
export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
|
||||
|
||||
export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
@@ -416,10 +434,16 @@ export const ServerSettings = Schema.Struct({
|
||||
Schema.withDecodingDefault(
|
||||
Effect.succeed({
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
model: DEFAULT_TEXT_GENERATION_MODEL,
|
||||
}),
|
||||
),
|
||||
),
|
||||
sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed({})),
|
||||
),
|
||||
sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
|
||||
// Legacy single-instance-per-driver settings. Continues to be the source
|
||||
// of truth until `providerInstances` (below) lands per-driver migration
|
||||
@@ -545,6 +569,14 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
|
||||
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
|
||||
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
|
||||
sourceControlWritingStyle: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
mode: Schema.optionalKey(SourceControlWritingStyleMode),
|
||||
customInstructions: Schema.optionalKey(TrimmedString),
|
||||
followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
|
||||
observability: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
otlpTracesUrl: Schema.optionalKey(TrimmedString),
|
||||
|
||||
@@ -2,14 +2,17 @@ import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { createModelSelection } from "./model.ts";
|
||||
import {
|
||||
applyServerSettingsPatch,
|
||||
extractPersistedServerObservabilitySettings,
|
||||
isModelSelectionProviderEnabled,
|
||||
normalizePersistedServerSettingString,
|
||||
parsePersistedServerObservabilitySettings,
|
||||
resolveSourceControlWriterModelSelection,
|
||||
} from "./serverSettings.ts";
|
||||
|
||||
describe("serverSettings helpers", () => {
|
||||
@@ -161,6 +164,104 @@ describe("serverSettings helpers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces source control writer selection without retaining stale options", () => {
|
||||
const current = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
sourceControlWriterModelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("codex"),
|
||||
"gpt-5.4-mini",
|
||||
[{ id: "reasoningEffort", value: "high" }],
|
||||
),
|
||||
};
|
||||
|
||||
expect(
|
||||
applyServerSettingsPatch(current, {
|
||||
sourceControlWriterModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
}).sourceControlWriterModelSelection,
|
||||
).toEqual({
|
||||
instanceId: "opencode",
|
||||
model: "openai/gpt-5",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears source control writer selection with null", () => {
|
||||
const current = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
sourceControlWriterModelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("codex"),
|
||||
"gpt-5.4-mini",
|
||||
),
|
||||
};
|
||||
|
||||
expect(
|
||||
applyServerSettingsPatch(current, {
|
||||
sourceControlWriterModelSelection: null,
|
||||
}).sourceControlWriterModelSelection,
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back from a disabled source control writer provider without clearing its selection", () => {
|
||||
const instanceId = ProviderInstanceId.make("codex_writer");
|
||||
const sourceControlWriterModelSelection = createModelSelection(instanceId, "gpt-5.4-mini");
|
||||
const settings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: false,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
};
|
||||
|
||||
expect(isModelSelectionProviderEnabled(settings, sourceControlWriterModelSelection)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(resolveSourceControlWriterModelSelection(settings)).toBe(
|
||||
settings.textGenerationModelSelection,
|
||||
);
|
||||
expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
|
||||
});
|
||||
|
||||
it("falls back from an unavailable source control writer provider", () => {
|
||||
const instanceId = ProviderInstanceId.make("missing_writer");
|
||||
const sourceControlWriterModelSelection = createModelSelection(instanceId, "missing-model");
|
||||
const settings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
};
|
||||
const unavailableProvider = {
|
||||
instanceId,
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
enabled: false,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "disabled",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-27T00:00:00.000Z",
|
||||
availability: "unavailable",
|
||||
unavailableReason: "This provider driver is not available in this build.",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
expect(resolveSourceControlWriterModelSelection(settings, [unavailableProvider])).toBe(
|
||||
settings.textGenerationModelSelection,
|
||||
);
|
||||
expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
|
||||
});
|
||||
|
||||
it("replaces providerInstances maps so omitted instance fields are cleared", () => {
|
||||
const codexId = ProviderInstanceId.make("codex");
|
||||
const current = {
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
isProviderAvailable,
|
||||
type ModelSelection,
|
||||
type ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
ServerSettings,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { deepMerge } from "./Struct.ts";
|
||||
@@ -8,6 +16,47 @@ import { createModelSelection } from "./model.ts";
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
const getLegacyProviderSettings = (
|
||||
settings: ServerSettings,
|
||||
provider: ProviderDriverKind,
|
||||
): LegacyProviderSettings | undefined =>
|
||||
(settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
|
||||
|
||||
export function isModelSelectionProviderEnabled(
|
||||
settings: ServerSettings,
|
||||
selection: ModelSelection,
|
||||
): boolean {
|
||||
const instanceConfig = settings.providerInstances[selection.instanceId];
|
||||
if (instanceConfig !== undefined) {
|
||||
return instanceConfig.enabled ?? true;
|
||||
}
|
||||
|
||||
return (
|
||||
isProviderDriverKind(selection.instanceId) &&
|
||||
getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveSourceControlWriterModelSelection(
|
||||
settings: ServerSettings,
|
||||
providers?: ReadonlyArray<ServerProvider>,
|
||||
): ModelSelection {
|
||||
const selection = settings.sourceControlWriterModelSelection;
|
||||
if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
|
||||
return settings.textGenerationModelSelection;
|
||||
}
|
||||
if (providers === undefined) {
|
||||
return selection;
|
||||
}
|
||||
|
||||
const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
|
||||
return provider?.enabled === true && isProviderAvailable(provider)
|
||||
? selection
|
||||
: settings.textGenerationModelSelection;
|
||||
}
|
||||
|
||||
export interface PersistedServerObservabilitySettings {
|
||||
readonly otlpTracesUrl: string | undefined;
|
||||
readonly otlpMetricsUrl: string | undefined;
|
||||
@@ -66,11 +115,6 @@ function mergeModelSelectionOptionsById(input: {
|
||||
return [...merged.entries()].map(([id, value]) => ({ id, value }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a server settings patch while treating textGenerationModelSelection as
|
||||
* replace-on-provider/model updates. This prevents stale nested options from
|
||||
* surviving a reset patch that intentionally omits options.
|
||||
*/
|
||||
export function applyServerSettingsPatch(
|
||||
current: ServerSettings,
|
||||
patch: ServerSettingsPatch,
|
||||
@@ -83,6 +127,9 @@ export function applyServerSettingsPatch(
|
||||
...(patch.providerInstances !== undefined
|
||||
? { providerInstances: patch.providerInstances }
|
||||
: {}),
|
||||
...(patch.sourceControlWriterModelSelection !== undefined
|
||||
? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
|
||||
: {}),
|
||||
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
|
||||
};
|
||||
if (!selectionPatch) {
|
||||
|
||||
Reference in new issue
Block a user