Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8c9d71187 | ||
|
|
3f089a454b | ||
|
|
b225dfaf77 |
No files matched your search
@@ -67,6 +67,7 @@ import {
|
|||||||
type TestProviderAdapterHarness,
|
type TestProviderAdapterHarness,
|
||||||
} from "./TestProviderAdapter.integration.ts";
|
} from "./TestProviderAdapter.integration.ts";
|
||||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||||
|
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -295,8 +296,10 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
providerLayer,
|
providerLayer,
|
||||||
RuntimeReceiptBusLive,
|
RuntimeReceiptBusLive,
|
||||||
);
|
);
|
||||||
|
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(serverSettingsLayer),
|
||||||
);
|
);
|
||||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
@@ -309,6 +312,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(gitCoreLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(textGenerationLayer),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
|
Layer.provideMerge(serverSettingsLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export interface ServerDerivedPaths {
|
|||||||
readonly stateDir: string;
|
readonly stateDir: string;
|
||||||
readonly dbPath: string;
|
readonly dbPath: string;
|
||||||
readonly keybindingsConfigPath: string;
|
readonly keybindingsConfigPath: string;
|
||||||
|
readonly settingsPath: string;
|
||||||
readonly worktreesDir: string;
|
readonly worktreesDir: string;
|
||||||
readonly attachmentsDir: string;
|
readonly attachmentsDir: string;
|
||||||
readonly logsDir: string;
|
readonly logsDir: string;
|
||||||
@@ -60,6 +61,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
|||||||
stateDir,
|
stateDir,
|
||||||
dbPath,
|
dbPath,
|
||||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||||
|
settingsPath: join(stateDir, "settings.json"),
|
||||||
worktreesDir: join(baseDir, "worktrees"),
|
worktreesDir: join(baseDir, "worktrees"),
|
||||||
attachmentsDir,
|
attachmentsDir,
|
||||||
logsDir,
|
logsDir,
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import { expect } from "vitest";
|
|||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
prefix: "t3code-claude-text-generation-test-",
|
prefix: "t3code-claude-text-generation-test-",
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
sanitizePrTitle,
|
sanitizePrTitle,
|
||||||
toJsonSchemaObject,
|
toJsonSchemaObject,
|
||||||
} from "../Utils.ts";
|
} from "../Utils.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
@@ -40,6 +41,7 @@ const ClaudeOutputEnvelope = Schema.Struct({
|
|||||||
|
|
||||||
const makeClaudeTextGeneration = Effect.gen(function* () {
|
const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
const readStreamAsString = <E>(
|
||||||
operation: string,
|
operation: string,
|
||||||
@@ -86,9 +88,14 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
|||||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const claudeSettings = yield* Effect.map(
|
||||||
|
serverSettingsService.getSettings,
|
||||||
|
(settings) => settings.claude,
|
||||||
|
).pipe(Effect.catch(() => Effect.undefined));
|
||||||
|
|
||||||
const runClaudeCommand = Effect.gen(function* () {
|
const runClaudeCommand = Effect.gen(function* () {
|
||||||
const command = ChildProcess.make(
|
const command = ChildProcess.make(
|
||||||
"claude",
|
claudeSettings?.binaryPath || "claude",
|
||||||
[
|
[
|
||||||
"-p",
|
"-p",
|
||||||
"--output-format",
|
"--output-format",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { ServerConfig } from "../../config.ts";
|
|||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||||
provider: "codex" as const,
|
provider: "codex" as const,
|
||||||
@@ -14,6 +15,7 @@ const DEFAULT_TEST_MODEL_SELECTION = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
prefix: "t3code-codex-text-generation-test-",
|
prefix: "t3code-codex-text-generation-test-",
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import {
|
|||||||
sanitizePrTitle,
|
sanitizePrTitle,
|
||||||
toJsonSchemaObject,
|
toJsonSchemaObject,
|
||||||
} from "../Utils.ts";
|
} from "../Utils.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||||
const CODEX_TIMEOUT_MS = 180_000;
|
const CODEX_TIMEOUT_MS = 180_000;
|
||||||
@@ -35,6 +36,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
const serverConfig = yield* Effect.service(ServerConfig);
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
|
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||||
|
|
||||||
type MaterializedImageAttachments = {
|
type MaterializedImageAttachments = {
|
||||||
readonly imagePaths: ReadonlyArray<string>;
|
readonly imagePaths: ReadonlyArray<string>;
|
||||||
@@ -138,6 +140,11 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
);
|
);
|
||||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||||
|
|
||||||
|
const codexSettings = yield* Effect.map(
|
||||||
|
serverSettingsService.getSettings,
|
||||||
|
(settings) => settings.codex,
|
||||||
|
).pipe(Effect.catch(() => Effect.undefined));
|
||||||
|
|
||||||
const runCodexCommand = Effect.gen(function* () {
|
const runCodexCommand = Effect.gen(function* () {
|
||||||
const normalizedOptions = normalizeCodexModelOptions(
|
const normalizedOptions = normalizeCodexModelOptions(
|
||||||
modelSelection.model,
|
modelSelection.model,
|
||||||
@@ -146,7 +153,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
const reasoningEffort =
|
const reasoningEffort =
|
||||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||||
const command = ChildProcess.make(
|
const command = ChildProcess.make(
|
||||||
"codex",
|
codexSettings?.binaryPath || "codex",
|
||||||
[
|
[
|
||||||
"exec",
|
"exec",
|
||||||
"--ephemeral",
|
"--ephemeral",
|
||||||
@@ -165,6 +172,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
"-",
|
"-",
|
||||||
],
|
],
|
||||||
{
|
{
|
||||||
|
env: codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {},
|
||||||
cwd,
|
cwd,
|
||||||
shell: process.platform === "win32",
|
shell: process.platform === "win32",
|
||||||
stdin: {
|
stdin: {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import * as ConfigProvider from "effect/ConfigProvider";
|
|||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as FileSystem from "effect/FileSystem";
|
import * as FileSystem from "effect/FileSystem";
|
||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
|
import * as Stream from "effect/Stream";
|
||||||
import * as Command from "effect/unstable/cli/Command";
|
import * as Command from "effect/unstable/cli/Command";
|
||||||
import { FetchHttpClient } from "effect/unstable/http";
|
import { FetchHttpClient } from "effect/unstable/http";
|
||||||
import { beforeEach } from "vitest";
|
import { beforeEach } from "vitest";
|
||||||
@@ -16,7 +17,9 @@ import { ServerConfig, type ServerConfigShape } from "./config";
|
|||||||
import { Open, type OpenShape } from "./open";
|
import { Open, type OpenShape } from "./open";
|
||||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||||
|
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||||
import { Server, type ServerShape } from "./wsServer";
|
import { Server, type ServerShape } from "./wsServer";
|
||||||
|
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings";
|
||||||
|
|
||||||
const start = vi.fn(() => undefined);
|
const start = vi.fn(() => undefined);
|
||||||
const stop = vi.fn(() => undefined);
|
const stop = vi.fn(() => undefined);
|
||||||
@@ -52,6 +55,13 @@ const testLayer = Layer.mergeAll(
|
|||||||
openBrowser: (_target: string) => Effect.void,
|
openBrowser: (_target: string) => Effect.void,
|
||||||
openInEditor: () => Effect.void,
|
openInEditor: () => Effect.void,
|
||||||
} satisfies OpenShape),
|
} satisfies OpenShape),
|
||||||
|
Layer.succeed(ServerSettingsService, {
|
||||||
|
start: Effect.void,
|
||||||
|
ready: Effect.void,
|
||||||
|
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||||
|
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||||
|
streamChanges: Stream.empty,
|
||||||
|
} satisfies ServerSettingsShape),
|
||||||
AnalyticsService.layerTest,
|
AnalyticsService.layerTest,
|
||||||
FetchHttpClient.layer,
|
FetchHttpClient.layer,
|
||||||
NodeServices.layer,
|
NodeServices.layer,
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { ServerLoggerLive } from "./serverLogger";
|
|||||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||||
import { readBootstrapEnvelope } from "./bootstrap";
|
import { readBootstrapEnvelope } from "./bootstrap";
|
||||||
|
import { ServerSettingsLive } from "./serverSettings";
|
||||||
|
|
||||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||||
readonly message: string;
|
readonly message: string;
|
||||||
@@ -297,6 +298,7 @@ const LayerLive = (input: CliInput) =>
|
|||||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||||
Layer.provideMerge(ServerLoggerLive),
|
Layer.provideMerge(ServerLoggerLive),
|
||||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||||
|
Layer.provideMerge(ServerSettingsLive),
|
||||||
Layer.provideMerge(ServerConfigLive(input)),
|
Layer.provideMerge(ServerConfigLive(input)),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
|||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||||
@@ -214,6 +215,7 @@ describe("ProviderCommandReactor", () => {
|
|||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||||
),
|
),
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import {
|
import {
|
||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
CommandId,
|
CommandId,
|
||||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
|
||||||
EventId,
|
EventId,
|
||||||
type ModelSelection,
|
type ModelSelection,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
ProviderKind,
|
ProviderKind,
|
||||||
type ProviderStartOptions,
|
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
@@ -26,6 +24,7 @@ import {
|
|||||||
ProviderCommandReactor,
|
ProviderCommandReactor,
|
||||||
type ProviderCommandReactorShape,
|
type ProviderCommandReactorShape,
|
||||||
} from "../Services/ProviderCommandReactor.ts";
|
} from "../Services/ProviderCommandReactor.ts";
|
||||||
|
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
|
||||||
|
|
||||||
type ProviderIntentEvent = Extract<
|
type ProviderIntentEvent = Extract<
|
||||||
OrchestrationEvent,
|
OrchestrationEvent,
|
||||||
@@ -138,6 +137,7 @@ const make = Effect.gen(function* () {
|
|||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitCore;
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
|
const serverSettingsService = yield* ServerSettingsService;
|
||||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||||
@@ -151,7 +151,6 @@ const make = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
|
||||||
const threadModelSelections = new Map<string, ModelSelection>();
|
const threadModelSelections = new Map<string, ModelSelection>();
|
||||||
|
|
||||||
const appendProviderFailureActivity = (input: {
|
const appendProviderFailureActivity = (input: {
|
||||||
@@ -210,7 +209,6 @@ const make = Effect.gen(function* () {
|
|||||||
createdAt: string,
|
createdAt: string,
|
||||||
options?: {
|
options?: {
|
||||||
readonly modelSelection?: ModelSelection;
|
readonly modelSelection?: ModelSelection;
|
||||||
readonly providerOptions?: ProviderStartOptions;
|
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const readModel = yield* orchestrationEngine.getReadModel();
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
@@ -253,16 +251,18 @@ const make = Effect.gen(function* () {
|
|||||||
readonly resumeCursor?: unknown;
|
readonly resumeCursor?: unknown;
|
||||||
readonly provider?: ProviderKind;
|
readonly provider?: ProviderKind;
|
||||||
}) =>
|
}) =>
|
||||||
providerService.startSession(threadId, {
|
Effect.gen(function* () {
|
||||||
threadId,
|
const serverSettings = yield* serverSettingsService.getSettings;
|
||||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
const providerOptions = deriveProviderStartOptions(serverSettings);
|
||||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
return yield* providerService.startSession(threadId, {
|
||||||
modelSelection: desiredModelSelection,
|
threadId,
|
||||||
...(options?.providerOptions !== undefined
|
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||||
? { providerOptions: options.providerOptions }
|
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||||
: {}),
|
modelSelection: desiredModelSelection,
|
||||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
...(providerOptions !== undefined ? { providerOptions } : {}),
|
||||||
runtimeMode: desiredRuntimeMode,
|
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||||
|
runtimeMode: desiredRuntimeMode,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const bindSessionToThread = (session: ProviderSession) =>
|
const bindSessionToThread = (session: ProviderSession) =>
|
||||||
@@ -354,7 +354,6 @@ const make = Effect.gen(function* () {
|
|||||||
readonly messageText: string;
|
readonly messageText: string;
|
||||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
readonly modelSelection?: ModelSelection;
|
readonly modelSelection?: ModelSelection;
|
||||||
readonly providerOptions?: ProviderStartOptions;
|
|
||||||
readonly interactionMode?: "default" | "plan";
|
readonly interactionMode?: "default" | "plan";
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
}) {
|
}) {
|
||||||
@@ -362,13 +361,11 @@ const make = Effect.gen(function* () {
|
|||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
yield* ensureSessionForThread(
|
||||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
input.threadId,
|
||||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
input.createdAt,
|
||||||
});
|
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
||||||
if (input.providerOptions !== undefined) {
|
);
|
||||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
|
||||||
}
|
|
||||||
if (input.modelSelection !== undefined) {
|
if (input.modelSelection !== undefined) {
|
||||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||||
}
|
}
|
||||||
@@ -437,10 +434,10 @@ const make = Effect.gen(function* () {
|
|||||||
cwd,
|
cwd,
|
||||||
message: input.messageText,
|
message: input.messageText,
|
||||||
...(attachments.length > 0 ? { attachments } : {}),
|
...(attachments.length > 0 ? { attachments } : {}),
|
||||||
modelSelection: {
|
modelSelection: yield* Effect.map(
|
||||||
provider: "codex",
|
serverSettingsService.getSettings,
|
||||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
(settings) => settings.textGenerationModelSelection,
|
||||||
},
|
),
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.catch((error) =>
|
Effect.catch((error) =>
|
||||||
@@ -518,9 +515,6 @@ const make = Effect.gen(function* () {
|
|||||||
...(event.payload.modelSelection !== undefined
|
...(event.payload.modelSelection !== undefined
|
||||||
? { modelSelection: event.payload.modelSelection }
|
? { modelSelection: event.payload.modelSelection }
|
||||||
: {}),
|
: {}),
|
||||||
...(event.payload.providerOptions !== undefined
|
|
||||||
? { providerOptions: event.payload.providerOptions }
|
|
||||||
: {}),
|
|
||||||
interactionMode: event.payload.interactionMode,
|
interactionMode: event.payload.interactionMode,
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
}).pipe(
|
}).pipe(
|
||||||
@@ -686,14 +680,12 @@ const make = Effect.gen(function* () {
|
|||||||
if (!thread?.session || thread.session.status === "stopped") {
|
if (!thread?.session || thread.session.status === "stopped") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
|
||||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
yield* ensureSessionForThread(
|
||||||
...(cachedProviderOptions !== undefined
|
event.payload.threadId,
|
||||||
? { providerOptions: cachedProviderOptions }
|
event.occurredAt,
|
||||||
: {}),
|
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
|
||||||
...(cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}),
|
);
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case "thread.turn-start-requested":
|
case "thread.turn-start-requested":
|
||||||
|
|||||||
@@ -12,10 +12,12 @@ import {
|
|||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
CommandId,
|
CommandId,
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
|
DEFAULT_SERVER_SETTINGS,
|
||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderItemId,
|
ProviderItemId,
|
||||||
|
type ServerSettings,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -38,8 +40,20 @@ import {
|
|||||||
} from "../Services/OrchestrationEngine.ts";
|
} from "../Services/OrchestrationEngine.ts";
|
||||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
|
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
|
||||||
|
const settings: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, ...overrides };
|
||||||
|
return Layer.succeed(ServerSettingsService, {
|
||||||
|
start: Effect.void,
|
||||||
|
ready: Effect.void,
|
||||||
|
getSettings: Effect.succeed(settings),
|
||||||
|
updateSettings: () => Effect.succeed(settings),
|
||||||
|
streamChanges: Stream.empty,
|
||||||
|
} satisfies ServerSettingsShape);
|
||||||
|
}
|
||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
@@ -155,7 +169,7 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
async function createHarness() {
|
async function createHarness(options?: { serverSettings?: Partial<ServerSettings> }) {
|
||||||
const workspaceRoot = makeTempDir("t3-provider-project-");
|
const workspaceRoot = makeTempDir("t3-provider-project-");
|
||||||
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
||||||
const provider = createProviderServiceHarness();
|
const provider = createProviderServiceHarness();
|
||||||
@@ -169,6 +183,7 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(SqlitePersistenceMemory),
|
Layer.provideMerge(SqlitePersistenceMemory),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
|
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
@@ -1357,7 +1372,7 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
await Effect.runPromise(
|
await Effect.runPromise(
|
||||||
@@ -1371,7 +1386,6 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
text: "stream please",
|
text: "stream please",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
assistantDeliveryMode: "streaming",
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
type OrchestrationThreadActivity,
|
type OrchestrationThreadActivity,
|
||||||
type ProviderRuntimeEvent,
|
type ProviderRuntimeEvent,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effect";
|
import { Cache, Cause, Duration, Effect, Layer, Option, Stream } from "effect";
|
||||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||||
|
|
||||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
@@ -26,12 +26,12 @@ import {
|
|||||||
ProviderRuntimeIngestionService,
|
ProviderRuntimeIngestionService,
|
||||||
type ProviderRuntimeIngestionShape,
|
type ProviderRuntimeIngestionShape,
|
||||||
} from "../Services/ProviderRuntimeIngestion.ts";
|
} from "../Services/ProviderRuntimeIngestion.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||||
|
|
||||||
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
|
||||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||||
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
||||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
|
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
|
||||||
@@ -537,10 +537,7 @@ const make = Effect.gen(function* () {
|
|||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||||
|
const serverSettingsService = yield* ServerSettingsService;
|
||||||
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
|
|
||||||
DEFAULT_ASSISTANT_DELIVERY_MODE,
|
|
||||||
);
|
|
||||||
|
|
||||||
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
||||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||||
@@ -1048,7 +1045,10 @@ const make = Effect.gen(function* () {
|
|||||||
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
|
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
|
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||||
|
serverSettingsService.getSettings,
|
||||||
|
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||||
|
);
|
||||||
if (assistantDeliveryMode === "buffered") {
|
if (assistantDeliveryMode === "buffered") {
|
||||||
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
|
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
|
||||||
if (spillChunk.length > 0) {
|
if (spillChunk.length > 0) {
|
||||||
@@ -1256,11 +1256,7 @@ const make = Effect.gen(function* () {
|
|||||||
).pipe(Effect.asVoid);
|
).pipe(Effect.asVoid);
|
||||||
});
|
});
|
||||||
|
|
||||||
const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
|
const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
|
||||||
Ref.set(
|
|
||||||
assistantDeliveryModeRef,
|
|
||||||
event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
|
||||||
);
|
|
||||||
|
|
||||||
const processInput = (input: RuntimeIngestionInput) =>
|
const processInput = (input: RuntimeIngestionInput) =>
|
||||||
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
|
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
} from "./commandInvariants.ts";
|
} from "./commandInvariants.ts";
|
||||||
|
|
||||||
const nowIso = () => new Date().toISOString();
|
const nowIso = () => new Date().toISOString();
|
||||||
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
|
|
||||||
|
|
||||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||||
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
||||||
@@ -330,10 +329,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
...(command.modelSelection !== undefined
|
...(command.modelSelection !== undefined
|
||||||
? { modelSelection: command.modelSelection }
|
? { modelSelection: command.modelSelection }
|
||||||
: {}),
|
: {}),
|
||||||
...(command.providerOptions !== undefined
|
|
||||||
? { providerOptions: command.providerOptions }
|
|
||||||
: {}),
|
|
||||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
|
||||||
runtimeMode: targetThread.runtimeMode,
|
runtimeMode: targetThread.runtimeMode,
|
||||||
interactionMode: targetThread.interactionMode,
|
interactionMode: targetThread.interactionMode,
|
||||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||||
|
|||||||
@@ -0,0 +1,283 @@
|
|||||||
|
/**
|
||||||
|
* ServerSettings - Server-authoritative settings service.
|
||||||
|
*
|
||||||
|
* Owns persistence, validation, and change notification of settings that affect
|
||||||
|
* server-side behavior (binary paths, streaming mode, env mode, custom models,
|
||||||
|
* text generation model selection).
|
||||||
|
*
|
||||||
|
* Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
|
||||||
|
* Semaphore + FileSystem.watch for concurrency and external edit detection.
|
||||||
|
*
|
||||||
|
* @module ServerSettings
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
DEFAULT_SERVER_SETTINGS,
|
||||||
|
type ProviderStartOptions,
|
||||||
|
ServerSettings,
|
||||||
|
type ServerSettingsPatch,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import {
|
||||||
|
Cache,
|
||||||
|
Deferred,
|
||||||
|
Effect,
|
||||||
|
Exit,
|
||||||
|
FileSystem,
|
||||||
|
Layer,
|
||||||
|
Path,
|
||||||
|
PubSub,
|
||||||
|
Ref,
|
||||||
|
Schema,
|
||||||
|
SchemaGetter,
|
||||||
|
Scope,
|
||||||
|
ServiceMap,
|
||||||
|
Stream,
|
||||||
|
} from "effect";
|
||||||
|
import * as Semaphore from "effect/Semaphore";
|
||||||
|
import { ServerConfig } from "./config";
|
||||||
|
|
||||||
|
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
|
||||||
|
"ServerSettingsError",
|
||||||
|
{
|
||||||
|
settingsPath: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Server settings error at ${this.settingsPath}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerSettingsShape {
|
||||||
|
/** Start the settings runtime and attach file watching. */
|
||||||
|
readonly start: Effect.Effect<void, ServerSettingsError>;
|
||||||
|
|
||||||
|
/** Await settings runtime readiness. */
|
||||||
|
readonly ready: Effect.Effect<void, ServerSettingsError>;
|
||||||
|
|
||||||
|
/** Read the current settings. */
|
||||||
|
readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
|
||||||
|
|
||||||
|
/** Patch settings and persist. Returns the new full settings object. */
|
||||||
|
readonly updateSettings: (
|
||||||
|
patch: ServerSettingsPatch,
|
||||||
|
) => Effect.Effect<ServerSettings, ServerSettingsError>;
|
||||||
|
|
||||||
|
/** Stream of settings change events. */
|
||||||
|
readonly streamChanges: Stream.Stream<ServerSettings>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerSettingsService extends ServiceMap.Service<
|
||||||
|
ServerSettingsService,
|
||||||
|
ServerSettingsShape
|
||||||
|
>()("t3/serverSettings/ServerSettingsService") {
|
||||||
|
static readonly layerTest = (overrides: Partial<ServerSettings> = {}) =>
|
||||||
|
Layer.succeed(ServerSettingsService, {
|
||||||
|
start: Effect.void,
|
||||||
|
ready: Effect.void,
|
||||||
|
getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
|
||||||
|
updateSettings: () => Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
|
||||||
|
streamChanges: Stream.empty,
|
||||||
|
} satisfies ServerSettingsShape);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive `ProviderStartOptions` from server settings.
|
||||||
|
* Replaces the client-side `getProviderStartOptions()` function.
|
||||||
|
*/
|
||||||
|
export function deriveProviderStartOptions(
|
||||||
|
settings: ServerSettings,
|
||||||
|
): ProviderStartOptions | undefined {
|
||||||
|
const providerOptions: ProviderStartOptions = {
|
||||||
|
...(settings.codex
|
||||||
|
? {
|
||||||
|
codex: {
|
||||||
|
...(settings.codex.binaryPath ? { binaryPath: settings.codex.binaryPath } : {}),
|
||||||
|
...(settings.codex.homePath ? { homePath: settings.codex.homePath } : {}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(settings.claude?.binaryPath
|
||||||
|
? {
|
||||||
|
claudeAgent: {
|
||||||
|
binaryPath: settings.claude.binaryPath,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ServerSettingsJson = Schema.fromJsonString(ServerSettings);
|
||||||
|
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||||
|
SchemaGetter.stringifyJson({ space: 2 }),
|
||||||
|
);
|
||||||
|
const ServerSettingsPrettyJson = ServerSettingsJson.pipe(
|
||||||
|
Schema.encode({
|
||||||
|
decode: PrettyJsonString,
|
||||||
|
encode: PrettyJsonString,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const makeServerSettings = Effect.gen(function* () {
|
||||||
|
const { settingsPath } = yield* ServerConfig;
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const pathService = yield* Path.Path;
|
||||||
|
const writeSemaphore = yield* Semaphore.make(1);
|
||||||
|
const cacheKey = "settings" as const;
|
||||||
|
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
|
||||||
|
const startedRef = yield* Ref.make(false);
|
||||||
|
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
|
||||||
|
const watcherScope = yield* Scope.make("sequential");
|
||||||
|
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
|
||||||
|
|
||||||
|
const emitChange = (settings: ServerSettings) =>
|
||||||
|
PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
|
||||||
|
|
||||||
|
const readConfigExists = fs.exists(settingsPath).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new ServerSettingsError({
|
||||||
|
settingsPath,
|
||||||
|
detail: "failed to check settings file existence",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const readRawConfig = fs.readFileString(settingsPath).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new ServerSettingsError({
|
||||||
|
settingsPath,
|
||||||
|
detail: "failed to read settings file",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadSettingsFromDisk = Effect.gen(function* () {
|
||||||
|
if (!(yield* readConfigExists)) {
|
||||||
|
return DEFAULT_SERVER_SETTINGS;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = yield* readRawConfig;
|
||||||
|
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
|
||||||
|
if (decoded._tag === "Failure") {
|
||||||
|
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
|
||||||
|
path: settingsPath,
|
||||||
|
});
|
||||||
|
return DEFAULT_SERVER_SETTINGS;
|
||||||
|
}
|
||||||
|
return decoded.value;
|
||||||
|
});
|
||||||
|
|
||||||
|
const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
|
||||||
|
capacity: 1,
|
||||||
|
lookup: () => loadSettingsFromDisk,
|
||||||
|
});
|
||||||
|
|
||||||
|
const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
|
||||||
|
|
||||||
|
const writeSettingsAtomically = (settings: ServerSettings) => {
|
||||||
|
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||||
|
|
||||||
|
return Schema.encodeEffect(ServerSettingsPrettyJson)(settings).pipe(
|
||||||
|
Effect.map((encoded) => `${encoded}\n`),
|
||||||
|
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
|
||||||
|
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||||
|
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new ServerSettingsError({
|
||||||
|
settingsPath,
|
||||||
|
detail: "failed to write settings file",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const revalidateAndEmit = writeSemaphore.withPermits(1)(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* Cache.invalidate(settingsCache, cacheKey);
|
||||||
|
const settings = yield* getSettingsFromCache;
|
||||||
|
yield* emitChange(settings);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const startWatcher = Effect.gen(function* () {
|
||||||
|
const settingsDir = pathService.dirname(settingsPath);
|
||||||
|
const settingsFile = pathService.basename(settingsPath);
|
||||||
|
const settingsPathResolved = pathService.resolve(settingsPath);
|
||||||
|
|
||||||
|
yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) =>
|
||||||
|
new ServerSettingsError({
|
||||||
|
settingsPath,
|
||||||
|
detail: "failed to prepare settings directory",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||||
|
|
||||||
|
yield* Stream.runForEach(fs.watch(settingsDir), (event) => {
|
||||||
|
const isTargetEvent =
|
||||||
|
event.path === settingsFile ||
|
||||||
|
event.path === settingsPath ||
|
||||||
|
pathService.resolve(settingsDir, event.path) === settingsPathResolved;
|
||||||
|
if (!isTargetEvent) {
|
||||||
|
return Effect.void;
|
||||||
|
}
|
||||||
|
return revalidateAndEmitSafely;
|
||||||
|
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
|
||||||
|
});
|
||||||
|
|
||||||
|
const start = Effect.gen(function* () {
|
||||||
|
const alreadyStarted = yield* Ref.get(startedRef);
|
||||||
|
if (alreadyStarted) {
|
||||||
|
return yield* Deferred.await(startedDeferred);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* Ref.set(startedRef, true);
|
||||||
|
const startup = Effect.gen(function* () {
|
||||||
|
yield* startWatcher;
|
||||||
|
yield* Cache.invalidate(settingsCache, cacheKey);
|
||||||
|
yield* getSettingsFromCache;
|
||||||
|
});
|
||||||
|
|
||||||
|
const startupExit = yield* Effect.exit(startup);
|
||||||
|
if (startupExit._tag === "Failure") {
|
||||||
|
yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
|
||||||
|
return yield* Effect.failCause(startupExit.cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
start,
|
||||||
|
ready: Deferred.await(startedDeferred),
|
||||||
|
getSettings: getSettingsFromCache,
|
||||||
|
updateSettings: (patch) =>
|
||||||
|
writeSemaphore.withPermits(1)(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const current = yield* getSettingsFromCache;
|
||||||
|
const next: ServerSettings = { ...current, ...patch };
|
||||||
|
yield* writeSettingsAtomically(next);
|
||||||
|
yield* Cache.set(settingsCache, cacheKey, next);
|
||||||
|
yield* emitChange(next);
|
||||||
|
return next;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
get streamChanges() {
|
||||||
|
return Stream.fromPubSub(changesPubSub);
|
||||||
|
},
|
||||||
|
} satisfies ServerSettingsShape;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings);
|
||||||
@@ -53,6 +53,7 @@ import { GitCore } from "./git/Services/GitCore.ts";
|
|||||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||||
|
import { ServerSettingsService } from "./serverSettings.ts";
|
||||||
|
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||||
@@ -545,6 +546,7 @@ describe("WebSocket Server", () => {
|
|||||||
Layer.provideMerge(runtimeLayer),
|
Layer.provideMerge(runtimeLayer),
|
||||||
Layer.provideMerge(providerHealthLayer),
|
Layer.provideMerge(providerHealthLayer),
|
||||||
Layer.provideMerge(openLayer),
|
Layer.provideMerge(openLayer),
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
Layer.provideMerge(serverConfigLayer),
|
Layer.provideMerge(serverConfigLayer),
|
||||||
Layer.provideMerge(AnalyticsService.layerTest),
|
Layer.provideMerge(AnalyticsService.layerTest),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ import { createLogger } from "./logger";
|
|||||||
import { GitManager } from "./git/Services/GitManager.ts";
|
import { GitManager } from "./git/Services/GitManager.ts";
|
||||||
import { TerminalManager } from "./terminal/Services/Manager.ts";
|
import { TerminalManager } from "./terminal/Services/Manager.ts";
|
||||||
import { Keybindings } from "./keybindings";
|
import { Keybindings } from "./keybindings";
|
||||||
|
import { ServerSettingsService } from "./serverSettings";
|
||||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||||
@@ -216,6 +217,7 @@ export type ServerRuntimeServices =
|
|||||||
| GitCore
|
| GitCore
|
||||||
| TerminalManager
|
| TerminalManager
|
||||||
| Keybindings
|
| Keybindings
|
||||||
|
| ServerSettingsService
|
||||||
| Open
|
| Open
|
||||||
| AnalyticsService;
|
| AnalyticsService;
|
||||||
|
|
||||||
@@ -253,6 +255,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
const gitManager = yield* GitManager;
|
const gitManager = yield* GitManager;
|
||||||
const terminalManager = yield* TerminalManager;
|
const terminalManager = yield* TerminalManager;
|
||||||
const keybindingsManager = yield* Keybindings;
|
const keybindingsManager = yield* Keybindings;
|
||||||
|
const serverSettingsManager = yield* ServerSettingsService;
|
||||||
const providerHealth = yield* ProviderHealth;
|
const providerHealth = yield* ProviderHealth;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitCore;
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
@@ -295,6 +298,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
yield* readiness.markKeybindingsReady;
|
yield* readiness.markKeybindingsReady;
|
||||||
|
yield* serverSettingsManager.start.pipe(
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) => new ServerLifecycleError({ operation: "serverSettingsRuntimeStart", cause }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||||
readonly command: ClientOrchestrationCommand;
|
readonly command: ClientOrchestrationCommand;
|
||||||
@@ -618,6 +626,14 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
}),
|
}),
|
||||||
).pipe(Effect.forkIn(subscriptionsScope));
|
).pipe(Effect.forkIn(subscriptionsScope));
|
||||||
|
|
||||||
|
yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) =>
|
||||||
|
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||||
|
issues: [],
|
||||||
|
providers: providerStatuses,
|
||||||
|
settings,
|
||||||
|
}),
|
||||||
|
).pipe(Effect.forkIn(subscriptionsScope));
|
||||||
|
|
||||||
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
||||||
yield* readiness.markOrchestrationSubscriptionsReady;
|
yield* readiness.markOrchestrationSubscriptionsReady;
|
||||||
|
|
||||||
@@ -878,8 +894,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
return yield* terminalManager.close(body);
|
return yield* terminalManager.close(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
case WS_METHODS.serverGetConfig:
|
case WS_METHODS.serverGetConfig: {
|
||||||
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
|
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
|
||||||
|
const settings = yield* serverSettingsManager.getSettings;
|
||||||
return {
|
return {
|
||||||
cwd,
|
cwd,
|
||||||
keybindingsConfigPath,
|
keybindingsConfigPath,
|
||||||
@@ -887,7 +904,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
issues: keybindingsConfig.issues,
|
issues: keybindingsConfig.issues,
|
||||||
providers: providerStatuses,
|
providers: providerStatuses,
|
||||||
availableEditors,
|
availableEditors,
|
||||||
|
settings,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
case WS_METHODS.serverUpsertKeybinding: {
|
case WS_METHODS.serverUpsertKeybinding: {
|
||||||
const body = stripRequestTag(request.body);
|
const body = stripRequestTag(request.body);
|
||||||
@@ -895,6 +914,15 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
return { keybindings: keybindingsConfig, issues: [] };
|
return { keybindings: keybindingsConfig, issues: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case WS_METHODS.serverGetSettings: {
|
||||||
|
return yield* serverSettingsManager.getSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
case WS_METHODS.serverUpdateSettings: {
|
||||||
|
const body = stripRequestTag(request.body);
|
||||||
|
return yield* serverSettingsManager.updateSettings(body.patch);
|
||||||
|
}
|
||||||
|
|
||||||
default: {
|
default: {
|
||||||
const _exhaustiveCheck: never = request.body;
|
const _exhaustiveCheck: never = request.body;
|
||||||
return yield* new RouteRequestError({
|
return yield* new RouteRequestError({
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
import { Schema } from "effect";
|
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AppSettingsSchema,
|
|
||||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||||
DEFAULT_TIMESTAMP_FORMAT,
|
DEFAULT_TIMESTAMP_FORMAT,
|
||||||
getProviderStartOptions,
|
|
||||||
} from "./appSettings";
|
} from "./appSettings";
|
||||||
import {
|
import {
|
||||||
getAppModelOptions,
|
getAppModelOptions,
|
||||||
@@ -134,35 +131,6 @@ describe("provider-specific custom models", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getProviderStartOptions", () => {
|
|
||||||
it("returns only populated provider overrides", () => {
|
|
||||||
expect(
|
|
||||||
getProviderStartOptions({
|
|
||||||
claudeBinaryPath: "/usr/local/bin/claude",
|
|
||||||
codexBinaryPath: "",
|
|
||||||
codexHomePath: "/Users/you/.codex",
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
claudeAgent: {
|
|
||||||
binaryPath: "/usr/local/bin/claude",
|
|
||||||
},
|
|
||||||
codex: {
|
|
||||||
homePath: "/Users/you/.codex",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns undefined when no provider overrides are configured", () => {
|
|
||||||
expect(
|
|
||||||
getProviderStartOptions({
|
|
||||||
claudeBinaryPath: "",
|
|
||||||
codexBinaryPath: "",
|
|
||||||
codexHomePath: "",
|
|
||||||
}),
|
|
||||||
).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("provider-indexed custom model settings", () => {
|
describe("provider-indexed custom model settings", () => {
|
||||||
const settings = {
|
const settings = {
|
||||||
customCodexModels: ["custom/codex-model"],
|
customCodexModels: ["custom/codex-model"],
|
||||||
@@ -242,33 +210,6 @@ describe("provider-indexed custom model settings", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("AppSettingsSchema", () => {
|
|
||||||
it("fills decoding defaults for persisted settings that predate newer keys", () => {
|
|
||||||
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
|
|
||||||
|
|
||||||
expect(
|
|
||||||
decode(
|
|
||||||
JSON.stringify({
|
|
||||||
codexBinaryPath: "/usr/local/bin/codex",
|
|
||||||
confirmThreadDelete: false,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
).toMatchObject({
|
|
||||||
claudeBinaryPath: "",
|
|
||||||
codexBinaryPath: "/usr/local/bin/codex",
|
|
||||||
codexHomePath: "",
|
|
||||||
defaultThreadEnvMode: "local",
|
|
||||||
confirmThreadDelete: false,
|
|
||||||
enableAssistantStreaming: false,
|
|
||||||
sidebarProjectSortOrder: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
|
||||||
sidebarThreadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
|
||||||
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
|
|
||||||
customCodexModels: [],
|
|
||||||
customClaudeModels: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("resolveAppModelSelectionState", () => {
|
describe("resolveAppModelSelectionState", () => {
|
||||||
it("falls back to the default git-writing codex selection", () => {
|
it("falls back to the default git-writing codex selection", () => {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
+36
-107
@@ -1,121 +1,50 @@
|
|||||||
import { useCallback } from "react";
|
/**
|
||||||
import { Option, Schema } from "effect";
|
* App Settings - Backward-compatible shim.
|
||||||
|
*
|
||||||
|
* Re-exports the unified settings hook (`useSettings` / `useUpdateSettings`)
|
||||||
|
* as `useAppSettings()` so existing consumers continue to work without
|
||||||
|
* modification. New code should import from `~/hooks/useSettings` directly.
|
||||||
|
*
|
||||||
|
* Also re-exports type aliases and schema constants consumed by components
|
||||||
|
* that only need the type (e.g. `TimestampFormat`).
|
||||||
|
*/
|
||||||
|
import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
|
||||||
|
import { useSettings, useUpdateSettings, type UnifiedSettings } from "./hooks/useSettings";
|
||||||
import {
|
import {
|
||||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
DEFAULT_CLIENT_SETTINGS,
|
||||||
ModelSelection,
|
type ClientSettings,
|
||||||
type ProviderStartOptions,
|
type TimestampFormat,
|
||||||
} from "@t3tools/contracts";
|
type SidebarProjectSortOrder,
|
||||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
type SidebarThreadSortOrder,
|
||||||
import { EnvMode } from "./components/BranchToolbar.logic";
|
DEFAULT_TIMESTAMP_FORMAT,
|
||||||
import { normalizeCustomModelSlugs } from "./modelSelection";
|
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||||
|
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||||
|
} from "./clientSettings";
|
||||||
|
|
||||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
// ── Re-exports for downstream type consumers ─────────────────────────
|
||||||
|
|
||||||
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
export type { TimestampFormat, SidebarProjectSortOrder, SidebarThreadSortOrder };
|
||||||
export type TimestampFormat = typeof TimestampFormat.Type;
|
export {
|
||||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
DEFAULT_TIMESTAMP_FORMAT,
|
||||||
export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
|
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||||
export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
|
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||||
export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
|
};
|
||||||
export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
|
export type { UnifiedSettings };
|
||||||
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
|
|
||||||
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
|
|
||||||
|
|
||||||
const withDefaults =
|
// ── Backward-compat type alias ───────────────────────────────────────
|
||||||
<
|
|
||||||
S extends Schema.Top & Schema.WithoutConstructorDefault,
|
|
||||||
D extends S["~type.make.in"] & S["Encoded"],
|
|
||||||
>(
|
|
||||||
fallback: () => D,
|
|
||||||
) =>
|
|
||||||
(schema: S) =>
|
|
||||||
schema.pipe(
|
|
||||||
Schema.withConstructorDefault(() => Option.some(fallback())),
|
|
||||||
Schema.withDecodingDefault(() => fallback()),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const AppSettingsSchema = Schema.Struct({
|
export type AppSettings = UnifiedSettings;
|
||||||
claudeBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
|
||||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
|
||||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
|
||||||
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
|
|
||||||
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
|
|
||||||
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
|
|
||||||
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
|
|
||||||
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
|
|
||||||
withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
|
|
||||||
),
|
|
||||||
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
|
|
||||||
withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
|
|
||||||
),
|
|
||||||
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
|
|
||||||
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
|
||||||
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
|
||||||
textGenerationModelSelection: ModelSelection.pipe(
|
|
||||||
withDefaults(() => ({
|
|
||||||
provider: "codex" as const,
|
|
||||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
});
|
|
||||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
|
||||||
|
|
||||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
// ── Backward-compat hook ─────────────────────────────────────────────
|
||||||
|
|
||||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
|
||||||
return {
|
|
||||||
...settings,
|
|
||||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
|
||||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getProviderStartOptions(
|
|
||||||
settings: Pick<AppSettings, "claudeBinaryPath" | "codexBinaryPath" | "codexHomePath">,
|
|
||||||
): ProviderStartOptions | undefined {
|
|
||||||
const providerOptions: ProviderStartOptions = {
|
|
||||||
...(settings.codexBinaryPath || settings.codexHomePath
|
|
||||||
? {
|
|
||||||
codex: {
|
|
||||||
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
|
|
||||||
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(settings.claudeBinaryPath
|
|
||||||
? {
|
|
||||||
claudeAgent: {
|
|
||||||
binaryPath: settings.claudeBinaryPath,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
|
|
||||||
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useAppSettings() {
|
export function useAppSettings() {
|
||||||
const [settings, setSettings] = useLocalStorage(
|
const settings = useSettings();
|
||||||
APP_SETTINGS_STORAGE_KEY,
|
const { updateSettings, resetSettings, defaults } = useUpdateSettings();
|
||||||
DEFAULT_APP_SETTINGS,
|
|
||||||
AppSettingsSchema,
|
|
||||||
);
|
|
||||||
|
|
||||||
const updateSettings = useCallback(
|
|
||||||
(patch: Partial<AppSettings>) => {
|
|
||||||
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
|
|
||||||
},
|
|
||||||
[setSettings],
|
|
||||||
);
|
|
||||||
|
|
||||||
const resetSettings = useCallback(() => {
|
|
||||||
setSettings(DEFAULT_APP_SETTINGS);
|
|
||||||
}, [setSettings]);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
settings,
|
settings,
|
||||||
updateSettings,
|
updateSettings: (patch: Partial<AppSettings>) => updateSettings(patch),
|
||||||
resetSettings,
|
resetSettings,
|
||||||
defaults: DEFAULT_APP_SETTINGS,
|
defaults,
|
||||||
} as const;
|
} as const;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/**
|
||||||
|
* Client-only settings - persisted in localStorage.
|
||||||
|
*
|
||||||
|
* These settings affect only the frontend UX and never need to be read by
|
||||||
|
* the server. Server-authoritative settings live in `ServerSettings`
|
||||||
|
* (defined in `@t3tools/contracts/server`).
|
||||||
|
*/
|
||||||
|
import { Option, Schema } from "effect";
|
||||||
|
|
||||||
|
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||||
|
|
||||||
|
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
||||||
|
export type TimestampFormat = typeof TimestampFormat.Type;
|
||||||
|
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||||
|
|
||||||
|
export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
|
||||||
|
export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
|
||||||
|
export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
|
||||||
|
|
||||||
|
export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
|
||||||
|
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
|
||||||
|
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
|
||||||
|
|
||||||
|
const withDefaults =
|
||||||
|
<
|
||||||
|
S extends Schema.Top & Schema.WithoutConstructorDefault,
|
||||||
|
D extends S["~type.make.in"] & S["Encoded"],
|
||||||
|
>(
|
||||||
|
fallback: () => D,
|
||||||
|
) =>
|
||||||
|
(schema: S) =>
|
||||||
|
schema.pipe(
|
||||||
|
Schema.withConstructorDefault(() => Option.some(fallback())),
|
||||||
|
Schema.withDecodingDefault(() => fallback()),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const ClientSettingsSchema = Schema.Struct({
|
||||||
|
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
|
||||||
|
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||||
|
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
|
||||||
|
withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
|
||||||
|
),
|
||||||
|
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
|
||||||
|
withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
|
||||||
|
),
|
||||||
|
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||||
|
});
|
||||||
|
export type ClientSettings = typeof ClientSettingsSchema.Type;
|
||||||
|
|
||||||
|
export const DEFAULT_CLIENT_SETTINGS: ClientSettings = ClientSettingsSchema.makeUnsafe({});
|
||||||
@@ -117,6 +117,15 @@ function createBaseServerConfig(): ServerConfig {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
availableEditors: [],
|
availableEditors: [],
|
||||||
|
settings: {
|
||||||
|
claude: { binaryPath: "" },
|
||||||
|
codex: { binaryPath: "", homePath: "" },
|
||||||
|
enableAssistantStreaming: false,
|
||||||
|
defaultThreadEnvMode: "local" as const,
|
||||||
|
customCodexModels: [],
|
||||||
|
customClaudeModels: [],
|
||||||
|
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ import {
|
|||||||
import { SidebarTrigger } from "./ui/sidebar";
|
import { SidebarTrigger } from "./ui/sidebar";
|
||||||
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
|
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
|
||||||
import { readNativeApi } from "~/nativeApi";
|
import { readNativeApi } from "~/nativeApi";
|
||||||
import { getProviderStartOptions, useAppSettings } from "../appSettings";
|
import { useAppSettings } from "../appSettings";
|
||||||
import {
|
import {
|
||||||
getCustomModelOptionsByProvider,
|
getCustomModelOptionsByProvider,
|
||||||
getCustomModelsByProvider,
|
getCustomModelsByProvider,
|
||||||
@@ -638,7 +638,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}),
|
}),
|
||||||
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
||||||
);
|
);
|
||||||
const providerOptionsForDispatch = useMemo(() => getProviderStartOptions(settings), [settings]);
|
|
||||||
const selectedModelForPicker = selectedModel;
|
const selectedModelForPicker = selectedModel;
|
||||||
const modelOptionsByProvider = useMemo(
|
const modelOptionsByProvider = useMemo(
|
||||||
() => getCustomModelOptionsByProvider(settings, selectedProvider, selectedModel),
|
() => getCustomModelOptionsByProvider(settings, selectedProvider, selectedModel),
|
||||||
@@ -2645,8 +2644,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
attachments: turnAttachments,
|
attachments: turnAttachments,
|
||||||
},
|
},
|
||||||
modelSelection: selectedModelSelection,
|
modelSelection: selectedModelSelection,
|
||||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
|
||||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
|
||||||
runtimeMode,
|
runtimeMode,
|
||||||
interactionMode,
|
interactionMode,
|
||||||
createdAt: messageCreatedAt,
|
createdAt: messageCreatedAt,
|
||||||
@@ -2927,8 +2924,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: selectedModelSelection,
|
modelSelection: selectedModelSelection,
|
||||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
|
||||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
|
||||||
runtimeMode,
|
runtimeMode,
|
||||||
interactionMode: nextInteractionMode,
|
interactionMode: nextInteractionMode,
|
||||||
...(nextInteractionMode === "default" && activeProposedPlan
|
...(nextInteractionMode === "default" && activeProposedPlan
|
||||||
@@ -2974,7 +2969,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
runtimeMode,
|
runtimeMode,
|
||||||
selectedPromptEffort,
|
selectedPromptEffort,
|
||||||
selectedModelSelection,
|
selectedModelSelection,
|
||||||
providerOptionsForDispatch,
|
|
||||||
selectedProvider,
|
selectedProvider,
|
||||||
setComposerDraftInteractionMode,
|
setComposerDraftInteractionMode,
|
||||||
setThreadError,
|
setThreadError,
|
||||||
@@ -3044,8 +3038,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
modelSelection: selectedModelSelection,
|
modelSelection: selectedModelSelection,
|
||||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
|
||||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
|
||||||
runtimeMode,
|
runtimeMode,
|
||||||
interactionMode: "default",
|
interactionMode: "default",
|
||||||
createdAt,
|
createdAt,
|
||||||
@@ -3096,9 +3088,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
runtimeMode,
|
runtimeMode,
|
||||||
selectedPromptEffort,
|
selectedPromptEffort,
|
||||||
selectedModelSelection,
|
selectedModelSelection,
|
||||||
providerOptionsForDispatch,
|
|
||||||
selectedProvider,
|
selectedProvider,
|
||||||
settings.enableAssistantStreaming,
|
|
||||||
syncServerReadModel,
|
syncServerReadModel,
|
||||||
selectedModel,
|
selectedModel,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -53,6 +53,15 @@ function createBaseServerConfig(): ServerConfig {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
availableEditors: [],
|
availableEditors: [],
|
||||||
|
settings: {
|
||||||
|
claude: { binaryPath: "" },
|
||||||
|
codex: { binaryPath: "", homePath: "" },
|
||||||
|
enableAssistantStreaming: false,
|
||||||
|
defaultThreadEnvMode: "local" as const,
|
||||||
|
customCodexModels: [],
|
||||||
|
customClaudeModels: [],
|
||||||
|
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
/**
|
||||||
|
* Unified settings hook.
|
||||||
|
*
|
||||||
|
* Abstracts the split between server-authoritative settings (persisted in
|
||||||
|
* `settings.json` on the server, fetched via `server.getConfig`) and
|
||||||
|
* client-only settings (persisted in localStorage).
|
||||||
|
*
|
||||||
|
* Consumers use `useSettings(selector)` to read, and `useUpdateSettings()` to
|
||||||
|
* write. The hook transparently routes reads/writes to the correct backing
|
||||||
|
* store.
|
||||||
|
*/
|
||||||
|
import { useCallback, useMemo } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { ServerSettings, ServerSettingsPatch, ServerConfig } from "@t3tools/contracts";
|
||||||
|
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||||
|
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||||
|
import { ensureNativeApi } from "~/nativeApi";
|
||||||
|
import { useLocalStorage } from "./useLocalStorage";
|
||||||
|
import {
|
||||||
|
ClientSettingsSchema,
|
||||||
|
type ClientSettings,
|
||||||
|
DEFAULT_CLIENT_SETTINGS,
|
||||||
|
CLIENT_SETTINGS_STORAGE_KEY,
|
||||||
|
} from "~/clientSettings";
|
||||||
|
import { Struct } from "effect";
|
||||||
|
|
||||||
|
// ── Unified type ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type UnifiedSettings = ServerSettings & ClientSettings;
|
||||||
|
|
||||||
|
// ── Key sets for routing patches ─────────────────────────────────────
|
||||||
|
|
||||||
|
const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
|
||||||
|
|
||||||
|
function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||||
|
serverPatch: ServerSettingsPatch;
|
||||||
|
clientPatch: Partial<ClientSettings>;
|
||||||
|
} {
|
||||||
|
const serverPatch: Record<string, unknown> = {};
|
||||||
|
const clientPatch: Record<string, unknown> = {};
|
||||||
|
for (const [key, value] of Object.entries(patch)) {
|
||||||
|
if (SERVER_SETTINGS_KEYS.has(key)) {
|
||||||
|
serverPatch[key] = value;
|
||||||
|
} else {
|
||||||
|
clientPatch[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
serverPatch: serverPatch as ServerSettingsPatch,
|
||||||
|
clientPatch: clientPatch as Partial<ClientSettings>,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Hooks ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read merged settings. Selector narrows the subscription so components
|
||||||
|
* only re-render when the slice they care about changes.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
|
||||||
|
selector?: (s: UnifiedSettings) => T,
|
||||||
|
): T {
|
||||||
|
const { data: serverConfig } = useQuery(serverConfigQueryOptions());
|
||||||
|
const [clientSettings] = useLocalStorage(
|
||||||
|
CLIENT_SETTINGS_STORAGE_KEY,
|
||||||
|
DEFAULT_CLIENT_SETTINGS,
|
||||||
|
ClientSettingsSchema,
|
||||||
|
);
|
||||||
|
|
||||||
|
const merged = useMemo<UnifiedSettings>(
|
||||||
|
() => ({
|
||||||
|
...(serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS),
|
||||||
|
...clientSettings,
|
||||||
|
}),
|
||||||
|
[serverConfig?.settings, clientSettings],
|
||||||
|
);
|
||||||
|
|
||||||
|
return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an updater that routes each key to the correct backing store.
|
||||||
|
*
|
||||||
|
* Server keys are optimistically patched in the React Query cache, then
|
||||||
|
* persisted via RPC. Client keys go straight to localStorage.
|
||||||
|
*/
|
||||||
|
export function useUpdateSettings() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [, setClientSettings] = useLocalStorage(
|
||||||
|
CLIENT_SETTINGS_STORAGE_KEY,
|
||||||
|
DEFAULT_CLIENT_SETTINGS,
|
||||||
|
ClientSettingsSchema,
|
||||||
|
);
|
||||||
|
|
||||||
|
const updateSettings = useCallback(
|
||||||
|
(patch: Partial<UnifiedSettings>) => {
|
||||||
|
const { serverPatch, clientPatch } = splitPatch(patch);
|
||||||
|
|
||||||
|
if (Object.keys(serverPatch).length > 0) {
|
||||||
|
// Optimistic update of the React Query cache
|
||||||
|
queryClient.setQueryData<ServerConfig>(serverQueryKeys.config(), (old) => {
|
||||||
|
if (!old) return old;
|
||||||
|
return {
|
||||||
|
...old,
|
||||||
|
settings: { ...old.settings, ...serverPatch },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
// Fire-and-forget RPC — push will reconcile on success
|
||||||
|
void ensureNativeApi().server.updateSettings(serverPatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(clientPatch).length > 0) {
|
||||||
|
setClientSettings((prev) => ({ ...prev, ...clientPatch }));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[queryClient, setClientSettings],
|
||||||
|
);
|
||||||
|
|
||||||
|
const resetSettings = useCallback(() => {
|
||||||
|
updateSettings({
|
||||||
|
...DEFAULT_SERVER_SETTINGS,
|
||||||
|
...DEFAULT_CLIENT_SETTINGS,
|
||||||
|
});
|
||||||
|
}, [updateSettings]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
updateSettings,
|
||||||
|
resetSettings,
|
||||||
|
defaults: { ...DEFAULT_SERVER_SETTINGS, ...DEFAULT_CLIENT_SETTINGS } as UnifiedSettings,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── One-time migration from localStorage ─────────────────────────────
|
||||||
|
|
||||||
|
const MIGRATION_FLAG_KEY = "t3code:settings-migrated:v1";
|
||||||
|
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call once on app startup. Migrates server-relevant settings from the
|
||||||
|
* old localStorage key to the server. Idempotent.
|
||||||
|
*/
|
||||||
|
export function migrateLocalSettingsToServer(): void {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
if (localStorage.getItem(MIGRATION_FLAG_KEY)) return;
|
||||||
|
|
||||||
|
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
|
||||||
|
if (!raw) {
|
||||||
|
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const old = JSON.parse(raw) as Record<string, unknown>;
|
||||||
|
const serverPatch: Record<string, unknown> = {};
|
||||||
|
for (const key of SERVER_SETTINGS_KEYS) {
|
||||||
|
if (key in old && old[key] !== undefined) {
|
||||||
|
serverPatch[key] = old[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate old flat binary-path keys into their new nested shape
|
||||||
|
const codexBinaryPath = old["codexBinaryPath"];
|
||||||
|
const codexHomePath = old["codexHomePath"];
|
||||||
|
const claudeBinaryPath = old["claudeBinaryPath"];
|
||||||
|
|
||||||
|
if (
|
||||||
|
(typeof codexBinaryPath === "string" && codexBinaryPath) ||
|
||||||
|
(typeof codexHomePath === "string" && codexHomePath)
|
||||||
|
) {
|
||||||
|
const existing = (serverPatch["codex"] as Record<string, unknown> | undefined) ?? {};
|
||||||
|
serverPatch["codex"] = {
|
||||||
|
...existing,
|
||||||
|
...(typeof codexBinaryPath === "string" && codexBinaryPath
|
||||||
|
? { binaryPath: codexBinaryPath }
|
||||||
|
: {}),
|
||||||
|
...(typeof codexHomePath === "string" && codexHomePath ? { homePath: codexHomePath } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof claudeBinaryPath === "string" && claudeBinaryPath) {
|
||||||
|
const existing = (serverPatch["claude"] as Record<string, unknown> | undefined) ?? {};
|
||||||
|
serverPatch["claude"] = {
|
||||||
|
...existing,
|
||||||
|
binaryPath: claudeBinaryPath,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(serverPatch).length > 0) {
|
||||||
|
void ensureNativeApi()
|
||||||
|
.server.updateSettings(serverPatch as ServerSettingsPatch)
|
||||||
|
.then(() => {
|
||||||
|
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// If parsing fails, mark as migrated to avoid retrying
|
||||||
|
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ import { useStore } from "../store";
|
|||||||
import { useTerminalStateStore } from "../terminalStateStore";
|
import { useTerminalStateStore } from "../terminalStateStore";
|
||||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||||
|
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||||
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
|
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
|
||||||
@@ -230,6 +231,8 @@ function EventRouter() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
const unsubWelcome = onServerWelcome((payload) => {
|
const unsubWelcome = onServerWelcome((payload) => {
|
||||||
|
// Migrate old localStorage settings to server on first connect
|
||||||
|
migrateLocalSettingsToServer();
|
||||||
void (async () => {
|
void (async () => {
|
||||||
await syncSnapshot();
|
await syncSnapshot();
|
||||||
if (disposed) {
|
if (disposed) {
|
||||||
|
|||||||
@@ -195,8 +195,8 @@ function SettingsRouteView() {
|
|||||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||||
const [openInstallProviders, setOpenInstallProviders] = useState<Record<ProviderKind, boolean>>({
|
const [openInstallProviders, setOpenInstallProviders] = useState<Record<ProviderKind, boolean>>({
|
||||||
codex: Boolean(settings.codexBinaryPath || settings.codexHomePath),
|
codex: Boolean(settings.codex?.binaryPath || settings.codex?.homePath),
|
||||||
claudeAgent: Boolean(settings.claudeBinaryPath),
|
claudeAgent: Boolean(settings.claude?.binaryPath),
|
||||||
});
|
});
|
||||||
const [selectedCustomModelProvider, setSelectedCustomModelProvider] =
|
const [selectedCustomModelProvider, setSelectedCustomModelProvider] =
|
||||||
useState<ProviderKind>("codex");
|
useState<ProviderKind>("codex");
|
||||||
@@ -211,9 +211,9 @@ function SettingsRouteView() {
|
|||||||
>({});
|
>({});
|
||||||
const [showAllCustomModels, setShowAllCustomModels] = useState(false);
|
const [showAllCustomModels, setShowAllCustomModels] = useState(false);
|
||||||
|
|
||||||
const codexBinaryPath = settings.codexBinaryPath;
|
const codexBinaryPath = settings.codex?.binaryPath ?? "";
|
||||||
const codexHomePath = settings.codexHomePath;
|
const codexHomePath = settings.codex?.homePath ?? "";
|
||||||
const claudeBinaryPath = settings.claudeBinaryPath;
|
const claudeBinaryPath = settings.claude?.binaryPath ?? "";
|
||||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||||
|
|
||||||
@@ -244,9 +244,9 @@ function SettingsRouteView() {
|
|||||||
? savedCustomModelRows
|
? savedCustomModelRows
|
||||||
: savedCustomModelRows.slice(0, 5);
|
: savedCustomModelRows.slice(0, 5);
|
||||||
const isInstallSettingsDirty =
|
const isInstallSettingsDirty =
|
||||||
settings.claudeBinaryPath !== defaults.claudeBinaryPath ||
|
settings.claude?.binaryPath !== defaults.claude?.binaryPath ||
|
||||||
settings.codexBinaryPath !== defaults.codexBinaryPath ||
|
settings.codex?.binaryPath !== defaults.codex?.binaryPath ||
|
||||||
settings.codexHomePath !== defaults.codexHomePath;
|
settings.codex?.homePath !== defaults.codex?.homePath;
|
||||||
const changedSettingLabels = [
|
const changedSettingLabels = [
|
||||||
...(theme !== "system" ? ["Theme"] : []),
|
...(theme !== "system" ? ["Theme"] : []),
|
||||||
...(settings.timestampFormat !== defaults.timestampFormat ? ["Time format"] : []),
|
...(settings.timestampFormat !== defaults.timestampFormat ? ["Time format"] : []),
|
||||||
@@ -831,9 +831,11 @@ function SettingsRouteView() {
|
|||||||
label="provider installs"
|
label="provider installs"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
updateSettings({
|
updateSettings({
|
||||||
claudeBinaryPath: defaults.claudeBinaryPath,
|
claude: { binaryPath: defaults.claude?.binaryPath ?? "" },
|
||||||
codexBinaryPath: defaults.codexBinaryPath,
|
codex: {
|
||||||
codexHomePath: defaults.codexHomePath,
|
binaryPath: defaults.codex?.binaryPath ?? "",
|
||||||
|
homePath: defaults.codex?.homePath ?? "",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
setOpenInstallProviders({
|
setOpenInstallProviders({
|
||||||
codex: false,
|
codex: false,
|
||||||
@@ -850,12 +852,12 @@ function SettingsRouteView() {
|
|||||||
const isOpen = openInstallProviders[providerSettings.provider];
|
const isOpen = openInstallProviders[providerSettings.provider];
|
||||||
const isDirty =
|
const isDirty =
|
||||||
providerSettings.provider === "codex"
|
providerSettings.provider === "codex"
|
||||||
? settings.codexBinaryPath !== defaults.codexBinaryPath ||
|
? settings.codex?.binaryPath !== defaults.codex?.binaryPath ||
|
||||||
settings.codexHomePath !== defaults.codexHomePath
|
settings.codex?.homePath !== defaults.codex?.homePath
|
||||||
: settings.claudeBinaryPath !== defaults.claudeBinaryPath;
|
: settings.claude?.binaryPath !== defaults.claude?.binaryPath;
|
||||||
const binaryPathValue =
|
const binaryPathValue =
|
||||||
providerSettings.binaryPathKey === "claudeBinaryPath"
|
providerSettings.binaryPathKey === "claudeBinaryPath"
|
||||||
? claudeBinaryPath
|
? (settings.claude?.binaryPath ?? "")
|
||||||
: codexBinaryPath;
|
: codexBinaryPath;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -910,9 +912,19 @@ function SettingsRouteView() {
|
|||||||
value={binaryPathValue}
|
value={binaryPathValue}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
updateSettings(
|
updateSettings(
|
||||||
providerSettings.binaryPathKey === "claudeBinaryPath"
|
providerSettings.provider === "claudeAgent"
|
||||||
? { claudeBinaryPath: event.target.value }
|
? {
|
||||||
: { codexBinaryPath: event.target.value },
|
claude: {
|
||||||
|
...settings.claude,
|
||||||
|
binaryPath: event.target.value,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
codex: {
|
||||||
|
...settings.codex,
|
||||||
|
binaryPath: event.target.value,
|
||||||
|
},
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
placeholder={providerSettings.binaryPlaceholder}
|
placeholder={providerSettings.binaryPlaceholder}
|
||||||
@@ -937,7 +949,10 @@ function SettingsRouteView() {
|
|||||||
value={codexHomePath}
|
value={codexHomePath}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
updateSettings({
|
updateSettings({
|
||||||
codexHomePath: event.target.value,
|
codex: {
|
||||||
|
...settings.codex,
|
||||||
|
homePath: event.target.value,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
placeholder={providerSettings.homePlaceholder}
|
placeholder={providerSettings.homePlaceholder}
|
||||||
|
|||||||
@@ -179,6 +179,8 @@ export function createWsNativeApi(): NativeApi {
|
|||||||
server: {
|
server: {
|
||||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||||
|
getSettings: () => transport.request(WS_METHODS.serverGetSettings),
|
||||||
|
updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }),
|
||||||
},
|
},
|
||||||
orchestration: {
|
orchestration: {
|
||||||
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
|
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import type {
|
|||||||
ProjectWriteFileInput,
|
ProjectWriteFileInput,
|
||||||
ProjectWriteFileResult,
|
ProjectWriteFileResult,
|
||||||
} from "./project";
|
} from "./project";
|
||||||
import type { ServerConfig } from "./server";
|
import type { ServerConfig, ServerSettings, ServerSettingsPatch } from "./server";
|
||||||
import type {
|
import type {
|
||||||
TerminalClearInput,
|
TerminalClearInput,
|
||||||
TerminalCloseInput,
|
TerminalCloseInput,
|
||||||
@@ -161,6 +161,8 @@ export interface NativeApi {
|
|||||||
server: {
|
server: {
|
||||||
getConfig: () => Promise<ServerConfig>;
|
getConfig: () => Promise<ServerConfig>;
|
||||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||||
|
getSettings: () => Promise<ServerSettings>;
|
||||||
|
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
|
||||||
};
|
};
|
||||||
orchestration: {
|
orchestration: {
|
||||||
getSnapshot: () => Promise<OrchestrationReadModel>;
|
getSnapshot: () => Promise<OrchestrationReadModel>;
|
||||||
|
|||||||
@@ -402,8 +402,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
|||||||
attachments: Schema.Array(ChatAttachment),
|
attachments: Schema.Array(ChatAttachment),
|
||||||
}),
|
}),
|
||||||
modelSelection: Schema.optional(ModelSelection),
|
modelSelection: Schema.optional(ModelSelection),
|
||||||
providerOptions: Schema.optional(ProviderStartOptions),
|
|
||||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
|
||||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||||
interactionMode: ProviderInteractionMode.pipe(
|
interactionMode: ProviderInteractionMode.pipe(
|
||||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||||
@@ -423,8 +421,6 @@ const ClientThreadTurnStartCommand = Schema.Struct({
|
|||||||
attachments: Schema.Array(UploadChatAttachment),
|
attachments: Schema.Array(UploadChatAttachment),
|
||||||
}),
|
}),
|
||||||
modelSelection: Schema.optional(ModelSelection),
|
modelSelection: Schema.optional(ModelSelection),
|
||||||
providerOptions: Schema.optional(ProviderStartOptions),
|
|
||||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
|
||||||
runtimeMode: RuntimeMode,
|
runtimeMode: RuntimeMode,
|
||||||
interactionMode: ProviderInteractionMode,
|
interactionMode: ProviderInteractionMode,
|
||||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||||
|
|||||||
@@ -1,8 +1,49 @@
|
|||||||
import { Schema } from "effect";
|
import { Schema, Struct } from "effect";
|
||||||
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
||||||
import { EditorId } from "./editor";
|
import { EditorId } from "./editor";
|
||||||
import { ProviderKind } from "./orchestration";
|
import { DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER } from "./model";
|
||||||
|
import { ModelSelection, ProviderKind } from "./orchestration";
|
||||||
|
|
||||||
|
// ── Server Settings (server-authoritative) ───────────────────────────
|
||||||
|
|
||||||
|
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
|
||||||
|
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
|
||||||
|
|
||||||
|
export const CodexSettings = Schema.Struct({
|
||||||
|
binaryPath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
|
||||||
|
homePath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
|
||||||
|
});
|
||||||
|
export type CodexSettings = typeof CodexSettings.Type;
|
||||||
|
|
||||||
|
export const ClaudeSettings = Schema.Struct({
|
||||||
|
binaryPath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
|
||||||
|
});
|
||||||
|
export type ClaudeSettings = typeof ClaudeSettings.Type;
|
||||||
|
|
||||||
|
export const ServerSettings = Schema.Struct({
|
||||||
|
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||||
|
claude: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||||
|
|
||||||
|
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
|
||||||
|
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||||
|
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
|
||||||
|
),
|
||||||
|
customCodexModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
|
||||||
|
customClaudeModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
|
||||||
|
textGenerationModelSelection: ModelSelection.pipe(
|
||||||
|
Schema.withDecodingDefault(() => ({
|
||||||
|
provider: "codex" as const,
|
||||||
|
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
export type ServerSettings = typeof ServerSettings.Type;
|
||||||
|
|
||||||
|
export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeUnknownSync(ServerSettings)({});
|
||||||
|
|
||||||
|
export const ServerSettingsPatch = ServerSettings.mapFields(Struct.map(Schema.optionalKey));
|
||||||
|
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
|
||||||
|
|
||||||
const KeybindingsMalformedConfigIssue = Schema.Struct({
|
const KeybindingsMalformedConfigIssue = Schema.Struct({
|
||||||
kind: Schema.Literal("keybindings.malformed-config"),
|
kind: Schema.Literal("keybindings.malformed-config"),
|
||||||
@@ -52,6 +93,7 @@ export const ServerConfig = Schema.Struct({
|
|||||||
issues: ServerConfigIssues,
|
issues: ServerConfigIssues,
|
||||||
providers: ServerProviderStatuses,
|
providers: ServerProviderStatuses,
|
||||||
availableEditors: Schema.Array(EditorId),
|
availableEditors: Schema.Array(EditorId),
|
||||||
|
settings: ServerSettings,
|
||||||
});
|
});
|
||||||
export type ServerConfig = typeof ServerConfig.Type;
|
export type ServerConfig = typeof ServerConfig.Type;
|
||||||
|
|
||||||
@@ -67,5 +109,6 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
|
|||||||
export const ServerConfigUpdatedPayload = Schema.Struct({
|
export const ServerConfigUpdatedPayload = Schema.Struct({
|
||||||
issues: ServerConfigIssues,
|
issues: ServerConfigIssues,
|
||||||
providers: ServerProviderStatuses,
|
providers: ServerProviderStatuses,
|
||||||
|
settings: Schema.optional(ServerSettings),
|
||||||
});
|
});
|
||||||
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
|
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
|
||||||
@@ -37,7 +37,7 @@ import {
|
|||||||
import { KeybindingRule } from "./keybindings";
|
import { KeybindingRule } from "./keybindings";
|
||||||
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
|
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
|
||||||
import { OpenInEditorInput } from "./editor";
|
import { OpenInEditorInput } from "./editor";
|
||||||
import { ServerConfigUpdatedPayload } from "./server";
|
import { ServerConfigUpdatedPayload, ServerSettingsPatch } from "./server";
|
||||||
|
|
||||||
// ── WebSocket RPC Method Names ───────────────────────────────────────
|
// ── WebSocket RPC Method Names ───────────────────────────────────────
|
||||||
|
|
||||||
@@ -76,6 +76,8 @@ export const WS_METHODS = {
|
|||||||
// Server meta
|
// Server meta
|
||||||
serverGetConfig: "server.getConfig",
|
serverGetConfig: "server.getConfig",
|
||||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||||
|
serverGetSettings: "server.getSettings",
|
||||||
|
serverUpdateSettings: "server.updateSettings",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// ── Push Event Channels ──────────────────────────────────────────────
|
// ── Push Event Channels ──────────────────────────────────────────────
|
||||||
@@ -141,6 +143,8 @@ const WebSocketRequestBody = Schema.Union([
|
|||||||
// Server meta
|
// Server meta
|
||||||
tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})),
|
tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})),
|
||||||
tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule),
|
tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule),
|
||||||
|
tagRequestBody(WS_METHODS.serverGetSettings, Schema.Struct({})),
|
||||||
|
tagRequestBody(WS_METHODS.serverUpdateSettings, Schema.Struct({ patch: ServerSettingsPatch })),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const WebSocketRequest = Schema.Struct({
|
export const WebSocketRequest = Schema.Struct({
|
||||||
|
|||||||
Reference in new issue
Block a user