Compare commits

...
Author SHA1 Message Date
Cursor Agent 2388e7d43f fix: prevent deepMerge from corrupting arrays by treating them as leaf values
P.isObject returns true for arrays, causing deepMerge to spread arrays
into plain objects with numeric keys and recursively merge entries.
This corrupted customModels arrays in ServerSettings whenever
updateSettings was called.

Add Array.isArray guards at both the top-level check and the per-key
recursive branch so arrays are replaced wholesale instead of merged.
2026-03-26 00:07:31 +00:00
Julius Marminge c91bd26b3c fix 2026-03-25 17:00:57 -07:00
Julius Marminge da0eaff9d4 rm reexport shi 2026-03-25 16:17:49 -07:00
Julius Marminge 7b0c9c0a9d kewl 2026-03-25 16:14:09 -07:00
Julius Marminge 007bd1755e kewl 2026-03-25 16:13:39 -07:00
Julius Marminge 5b750e2b1e use more lenient json parse 2026-03-25 16:05:30 -07:00
Julius Marminge d6099ed9ca fix expectation 2026-03-25 14:45:57 -07:00
Julius Marminge 69e5d81ef6 Default server settings providers object
- Allow server settings to decode without an explicit providers block
2026-03-25 14:39:36 -07:00
Julius Marminge 14e81b90b6 lint 2026-03-25 14:36:04 -07:00
Julius Marminge f942c3484a mv 2026-03-25 14:33:20 -07:00
38 changed files with 446 additions and 179 deletions

No files matched your search

+1 -1
View File
@@ -542,7 +542,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
};
const codexOptions = readCodexProviderOptions(input);
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
const codexBinaryPath = codexOptions.binaryPath || "codex";
const codexHomePath = codexOptions.homePath;
this.assertSupportedCodexCliVersion({
binaryPath: codexBinaryPath,
@@ -95,7 +95,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
const runClaudeCommand = Effect.gen(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath ?? "claude",
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
@@ -153,7 +153,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath ?? "codex",
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
@@ -20,11 +20,7 @@ import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "codex",
model: "gpt-5.4-mini",
} as const;
import { ServerSettingsService } from "../../serverSettings.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -466,7 +462,6 @@ function runStackedAction(
{
...input,
actionId: input.actionId ?? "test-action-id",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
},
options,
);
@@ -493,6 +488,8 @@ function makeManager(input?: {
prefix: "t3-git-manager-test-",
});
const serverSettingsLayer = ServerSettingsService.layerTest();
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
@@ -502,6 +499,7 @@ function makeManager(input?: {
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
gitCoreLayer,
serverSettingsLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
return makeGitManager.pipe(
+12 -3
View File
@@ -19,6 +19,7 @@ import {
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -358,6 +359,7 @@ export const makeGitManager = Effect.gen(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = (
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
@@ -1173,6 +1175,13 @@ export const makeGitManager = Effect.gen(function* () {
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
const modelSelection = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.textGenerationModelSelection),
Effect.mapError((cause) =>
gitManagerError("runStackedAction", "Failed to get server settings.", cause),
),
);
if (input.featureBranch) {
currentPhase = "branch";
yield* progress.emit({
@@ -1181,7 +1190,7 @@ export const makeGitManager = Effect.gen(function* () {
label: "Preparing feature branch...",
});
const result = yield* runFeatureBranchStep(
input.modelSelection,
modelSelection,
input.cwd,
initialStatus.branch,
input.commitMessage,
@@ -1198,7 +1207,7 @@ export const makeGitManager = Effect.gen(function* () {
currentPhase = "commit";
const commit = yield* runCommitStep(
input.modelSelection,
modelSelection,
input.cwd,
input.action,
currentBranch,
@@ -1237,7 +1246,7 @@ export const makeGitManager = Effect.gen(function* () {
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "pr";
return yield* runPrStep(input.modelSelection, input.cwd, currentBranch);
return yield* runPrStep(modelSelection, input.cwd, currentBranch);
}),
),
)
+22 -11
View File
@@ -23,6 +23,7 @@ import {
Cache,
Cause,
Deferred,
Duration,
Effect,
Exit,
FileSystem,
@@ -42,6 +43,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -408,7 +410,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
@@ -817,16 +819,25 @@ const makeKeybindings = Effect.gen(function* () {
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
const isTargetConfigEvent =
event.path === keybindingsConfigFile ||
event.path === keybindingsConfigPath ||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
if (!isTargetConfigEvent) {
return Effect.void;
}
return revalidateAndEmitSafely;
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
// Debounce watch events so the file is fully written before we read it.
// Editors emit multiple events per save (truncate, write, rename) and
// `fs.watch` can fire before the content has been flushed to disk.
const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
Stream.filter((event) => {
return (
event.path === keybindingsConfigFile ||
event.path === keybindingsConfigPath ||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
);
}),
Stream.debounce(Duration.millis(100)),
);
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkIn(watcherScope),
Effect.asVoid,
);
});
const start = Effect.gen(function* () {
@@ -188,7 +188,6 @@ describe("decider project scripts", () => {
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
@@ -2751,7 +2751,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
pathToClaudeCodeExecutable: providerOptions?.binaryPath || "claude",
settingSources: [...CLAUDE_SETTING_SOURCES],
...(effectiveEffort ? { effort: effectiveEffort } : {}),
...(permissionMode ? { permissionMode } : {}),
+104
View File
@@ -0,0 +1,104 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { DEFAULT_SERVER_SETTINGS, ServerSettingsPatch } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { ServerConfig } from "./config";
import { ServerSettingsLive, ServerSettingsService } from "./serverSettings";
const makeServerSettingsLayer = () =>
ServerSettingsLive.pipe(
Layer.provideMerge(
Layer.fresh(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-server-settings-test-",
}),
),
),
);
it.layer(NodeServices.layer)("server settings", (it) => {
it.effect("decodes nested settings patches", () =>
Effect.sync(() => {
const decodePatch = Schema.decodeUnknownSync(ServerSettingsPatch);
assert.deepEqual(decodePatch({ providers: { codex: { binaryPath: "/tmp/codex" } } }), {
providers: { codex: { binaryPath: "/tmp/codex" } },
});
assert.deepEqual(
decodePatch({
textGenerationModelSelection: {
options: {
fastMode: false,
},
},
}),
{
textGenerationModelSelection: {
options: {
fastMode: false,
},
},
},
);
}),
);
it.effect("deep merges nested settings updates without dropping siblings", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: "/usr/local/bin/codex",
homePath: "/Users/julius/.codex",
},
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
customModels: ["claude-custom"],
},
},
textGenerationModelSelection: {
provider: "codex",
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
options: {
reasoningEffort: "high",
fastMode: true,
},
},
});
const next = yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
},
},
textGenerationModelSelection: {
options: {
fastMode: false,
},
},
});
assert.deepEqual(next.providers.codex, {
binaryPath: "/opt/homebrew/bin/codex",
homePath: "/Users/julius/.codex",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
binaryPath: "/usr/local/bin/claude",
customModels: ["claude-custom"],
});
assert.deepEqual(next.textGenerationModelSelection, {
provider: "codex",
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
options: {
reasoningEffort: "high",
fastMode: false,
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
});
+24 -12
View File
@@ -19,6 +19,7 @@ import {
import {
Cache,
Deferred,
Duration,
Effect,
Exit,
FileSystem,
@@ -34,6 +35,8 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
"ServerSettingsError",
@@ -113,7 +116,7 @@ export function deriveProviderStartOptions(
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
}
const ServerSettingsJson = Schema.fromJsonString(ServerSettings);
const ServerSettingsJson = fromLenientJson(ServerSettings);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
@@ -229,16 +232,25 @@ const makeServerSettings = Effect.gen(function* () {
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);
// Debounce watch events so the file is fully written before we read it.
// Editors emit multiple events per save (truncate, write, rename) and
// `fs.watch` can fire before the content has been flushed to disk.
const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
Stream.filter((event) => {
return (
event.path === settingsFile ||
event.path === settingsPath ||
pathService.resolve(settingsDir, event.path) === settingsPathResolved
);
}),
Stream.debounce(Duration.millis(100)),
);
yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkIn(watcherScope),
Effect.asVoid,
);
});
const start = Effect.gen(function* () {
@@ -271,7 +283,7 @@ const makeServerSettings = Effect.gen(function* () {
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const next: ServerSettings = { ...current, ...patch };
const next = deepMerge(current, patch);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
+12 -6
View File
@@ -13,11 +13,13 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
import {
DEFAULT_TERMINAL_ID,
DEFAULT_SERVER_SETTINGS,
EDITORS,
EventId,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
ProviderItemId,
type ServerSettings,
ThreadId,
TurnId,
WS_CHANNELS,
@@ -79,6 +81,8 @@ const defaultProviderHealthService: ProviderHealthShape = {
getStatuses: Effect.succeed(defaultProviderStatuses),
};
const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly listeners = new Set<(event: TerminalEvent) => void>();
@@ -493,6 +497,7 @@ describe("WebSocket Server", () => {
gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
terminalManager?: TerminalManagerShape;
serverSettings?: Partial<ServerSettings>;
} = {},
): Promise<Http.Server> {
if (serverScope) {
@@ -546,7 +551,7 @@ describe("WebSocket Server", () => {
Layer.provideMerge(runtimeLayer),
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
Layer.provideMerge(serverConfigLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provideMerge(NodeServices.layer),
@@ -860,6 +865,7 @@ describe("WebSocket Server", () => {
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
settings: defaultServerSettings,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
});
@@ -885,6 +891,7 @@ describe("WebSocket Server", () => {
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
settings: defaultServerSettings,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -921,6 +928,7 @@ describe("WebSocket Server", () => {
],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
settings: defaultServerSettings,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
@@ -1071,6 +1079,7 @@ describe("WebSocket Server", () => {
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
settings: defaultServerSettings,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
});
@@ -1119,6 +1128,7 @@ describe("WebSocket Server", () => {
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
settings: defaultServerSettings,
});
expectAvailableEditors(
(configResponse.result as { availableEditors: unknown }).availableEditors,
@@ -1275,6 +1285,7 @@ describe("WebSocket Server", () => {
server = await createTestServer({
cwd: "/test",
providerLayer,
serverSettings: { enableAssistantStreaming: true },
});
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1325,7 +1336,6 @@ describe("WebSocket Server", () => {
text: "hello",
attachments: [],
},
assistantDeliveryMode: "streaming",
runtimeMode: "approval-required",
interactionMode: "default",
createdAt,
@@ -1852,10 +1862,6 @@ describe("WebSocket Server", () => {
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
},
expect.objectContaining({
actionId: "client-action-1",
-50
View File
@@ -1,50 +0,0 @@
/**
* 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 {
DEFAULT_CLIENT_SETTINGS,
type ClientSettings,
type TimestampFormat,
type SidebarProjectSortOrder,
type SidebarThreadSortOrder,
DEFAULT_TIMESTAMP_FORMAT,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "./clientSettings";
// ── Re-exports for downstream type consumers ─────────────────────────
export type { TimestampFormat, SidebarProjectSortOrder, SidebarThreadSortOrder };
export {
DEFAULT_TIMESTAMP_FORMAT,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
};
export type { UnifiedSettings };
// ── Backward-compat type alias ───────────────────────────────────────
export type AppSettings = UnifiedSettings;
// ── Backward-compat hook ─────────────────────────────────────────────
export function useAppSettings() {
const settings = useSettings();
const { updateSettings, resetSettings, defaults } = useUpdateSettings();
return {
settings,
updateSettings: (patch: Partial<AppSettings>) => updateSettings(patch),
resetSettings,
defaults,
} as const;
}
+2 -3
View File
@@ -120,7 +120,7 @@ import {
import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import { useAppSettings } from "../appSettings";
import { useSettings } from "../hooks/useSettings";
import { getCustomModelOptionsByProvider, resolveAppModelSelection } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import {
@@ -245,7 +245,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setStoreThreadError = useStore((store) => store.setError);
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
const { settings } = useAppSettings();
const settings = useSettings();
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
);
@@ -2967,7 +2967,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
selectedProvider,
setComposerDraftInteractionMode,
setThreadError,
settings.enableAssistantStreaming,
selectedModel,
],
);
+2 -2
View File
@@ -30,7 +30,7 @@ import { buildPatchCacheKey } from "../lib/diffRendering";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useStore } from "../store";
import { useAppSettings } from "../appSettings";
import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
@@ -166,7 +166,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { settings } = useAppSettings();
const settings = useSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const patchViewportRef = useRef<HTMLDivElement>(null);
@@ -20,7 +20,6 @@ import {
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
import { useAppSettings } from "~/appSettings";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import {
@@ -205,7 +204,6 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
}
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
const { settings } = useAppSettings();
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
@@ -261,7 +259,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
gitRunStackedActionMutationOptions({
cwd: gitCwd,
queryClient,
modelSelection: settings.textGenerationModelSelection,
}),
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
+1 -1
View File
@@ -1,5 +1,5 @@
import { memo, useState, useCallback } from "react";
import { type TimestampFormat } from "../appSettings";
import { type TimestampFormat } from "../clientSettings";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { ScrollArea } from "./ui/scroll-area";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../appSettings";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../clientSettings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
import {
+4 -6
View File
@@ -38,11 +38,7 @@ import {
} from "@t3tools/contracts";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
type SidebarProjectSortOrder,
type SidebarThreadSortOrder,
useAppSettings,
} from "../appSettings";
import { type SidebarProjectSortOrder, type SidebarThreadSortOrder } from "../clientSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
@@ -102,6 +98,7 @@ import {
sortThreadsForSidebar,
} from "./Sidebar.logic";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -381,7 +378,8 @@ export default function Sidebar() {
);
const navigate = useNavigate();
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
const { settings: appSettings, updateSettings } = useAppSettings();
const appSettings = useSettings();
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useHandleNewThread();
const routeThreadId = useParams({
strict: false,
@@ -48,7 +48,7 @@ import {
type ParsedTerminalContextEntry,
} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
import { type TimestampFormat } from "../../appSettings";
import { type TimestampFormat } from "../../clientSettings";
import { formatTimestamp } from "../../timestampFormat";
import {
buildInlineTerminalContextText,
@@ -114,7 +114,7 @@ async function mountClaudePicker(props?: {
? ({
provider: "claudeAgent",
model,
options: props.fallbackModelOptions ?? undefined,
...(props.fallbackModelOptions ? { options: props.fallbackModelOptions } : {}),
} satisfies ModelSelection)
: null;
const screen = await render(
+1 -1
View File
@@ -31,7 +31,7 @@ import {
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
import { UnifiedSettings } from "./appSettings";
import { UnifiedSettings } from "./hooks/useSettings";
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
const COMPOSER_DRAFT_STORAGE_VERSION = 3;
+83 -21
View File
@@ -11,18 +11,27 @@
*/
import { useCallback, useMemo } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ServerSettings, ServerSettingsPatch, ServerConfig } from "@t3tools/contracts";
import {
ServerSettings,
ServerSettingsPatch,
ServerConfig,
ModelSelection,
ThreadEnvMode,
} 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 { normalizeCustomModelSlugs } from "~/modelSelection";
import {
ClientSettingsSchema,
type ClientSettings,
DEFAULT_CLIENT_SETTINGS,
CLIENT_SETTINGS_STORAGE_KEY,
} from "~/clientSettings";
import { Struct } from "effect";
import { Predicate, Schema, Struct } from "effect";
import { DeepMutable } from "effect/Types";
import { deepMerge } from "@t3tools/shared/Struct";
// ── Unified type ─────────────────────────────────────────────────────
@@ -103,7 +112,7 @@ export function useUpdateSettings() {
if (!old) return old;
return {
...old,
settings: { ...old.settings, ...serverPatch },
settings: deepMerge(old.settings, serverPatch),
};
});
// Fire-and-forget RPC — push will reconcile on success
@@ -133,9 +142,63 @@ export function useUpdateSettings() {
// ── One-time migration from localStorage ─────────────────────────────
const MIGRATION_FLAG_KEY = "t3code:settings-migrated:v1";
const MIGRATION_FLAG_KEY = "t3code:settings-migrated";
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
const patch: DeepMutable<ServerSettingsPatch> = {};
if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
}
if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
}
if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
}
if (typeof legacySettings.codexBinaryPath === "string") {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
}
if (typeof legacySettings.codexHomePath === "string") {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.homePath = legacySettings.codexHomePath;
}
if (Array.isArray(legacySettings.customCodexModels)) {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.customModels = normalizeCustomModelSlugs(
legacySettings.customCodexModels,
"codex",
);
}
if (Predicate.isString(legacySettings.claudeBinaryPath)) {
patch.providers ??= {};
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
}
if (Array.isArray(legacySettings.customClaudeModels)) {
patch.providers ??= {};
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
legacySettings.customClaudeModels,
"claudeAgent",
);
}
return patch;
}
/**
* Call once on app startup. Migrates server-relevant settings from the
* old localStorage key to the server. Idempotent.
@@ -151,25 +214,24 @@ export function migrateLocalSettingsToServer(): void {
}
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];
}
const old = JSON.parse(raw);
if (!Predicate.isObject(old)) return;
const api = ensureNativeApi();
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
if (Object.keys(serverPatch).length === 0) {
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
return;
}
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
void api.server.updateSettings(serverPatch);
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
} catch (error) {
console.error("[MIGRATION] Error migrating local settings to server:", error);
} finally {
// Mark as migrated no matter what to avoid retrying
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
}
}
-4
View File
@@ -32,10 +32,6 @@ describe("git mutation options", () => {
const options = gitRunStackedActionMutationOptions({
cwd: "/repo/a",
queryClient,
modelSelection: {
provider: "codex",
model: "gpt-5.4",
},
});
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
});
+1 -3
View File
@@ -1,4 +1,4 @@
import { type GitStackedAction, type ModelSelection } from "@t3tools/contracts";
import { type GitStackedAction } from "@t3tools/contracts";
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
import { ensureNativeApi } from "../nativeApi";
@@ -112,7 +112,6 @@ export function gitCheckoutMutationOptions(input: {
export function gitRunStackedActionMutationOptions(input: {
cwd: string | null;
queryClient: QueryClient;
modelSelection: ModelSelection;
}) {
return mutationOptions({
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
@@ -134,7 +133,6 @@ export function gitRunStackedActionMutationOptions(input: {
return api.git.runStackedAction({
actionId,
cwd: input.cwd,
modelSelection: input.modelSelection,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
+7 -1
View File
@@ -6,6 +6,13 @@ export const serverQueryKeys = {
config: () => ["server", "config"] as const,
};
/**
* Server config query options.
*
* `staleTime` is kept short so that push-driven `invalidateQueries` calls in
* the EventRouter always trigger a refetch, and so the query re-fetches when
* the component re-mounts (e.g. navigating away from settings and back).
*/
export function serverConfigQueryOptions() {
return queryOptions({
queryKey: serverQueryKeys.config(),
@@ -13,6 +20,5 @@ export function serverConfigQueryOptions() {
const api = ensureNativeApi();
return api.server.getConfig();
},
staleTime: Infinity,
});
}
+1 -1
View File
@@ -10,7 +10,7 @@ import {
resolveSelectableModel,
} from "@t3tools/shared/model";
import { getComposerProviderState } from "./components/chat/composerProviderRegistry";
import { UnifiedSettings } from "./appSettings";
import { UnifiedSettings } from "./hooks/useSettings";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
+6
View File
@@ -263,8 +263,14 @@ function EventRouter() {
// don't produce duplicate toasts.
let subscribed = false;
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
// Invalidate the config query so active observers refetch fresh data.
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
if (!subscribed) return;
// Only show keybindings toasts for keybindings changes (no settings in payload)
if (payload.settings) return;
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
if (!issue) {
toastManager.add({
+3 -2
View File
@@ -4,7 +4,7 @@ import { ChevronDownIcon, PlusIcon, RotateCcwIcon, Undo2Icon, XIcon } from "luci
import { type ReactNode, useCallback, useState } from "react";
import { type ProviderKind } from "@t3tools/contracts";
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { useAppSettings } from "../appSettings";
import { useSettings, useUpdateSettings } from "../hooks/useSettings";
import {
getCustomModelOptionsByProvider,
MAX_CUSTOM_MODEL_LENGTH,
@@ -184,7 +184,8 @@ function SettingResetButton({ label, onClick }: { label: string; onClick: () =>
function SettingsRouteView() {
const { theme, setTheme } = useTheme();
const { settings, defaults, updateSettings, resetSettings } = useAppSettings();
const settings = useSettings();
const { updateSettings, resetSettings, defaults } = useUpdateSettings();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
+2 -2
View File
@@ -11,7 +11,7 @@ import { resolveShortcutCommand } from "../keybindings";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
import { useAppSettings } from "~/appSettings";
import { useSettings } from "~/hooks/useSettings";
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
@@ -31,7 +31,7 @@ function ChatRouteGlobalShortcuts() {
? selectThreadTerminalState(state.terminalStateByThreadId, routeThreadId).terminalOpen
: false,
);
const { settings: appSettings } = useAppSettings();
const appSettings = useSettings();
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
+1 -1
View File
@@ -1,4 +1,4 @@
import { type TimestampFormat } from "./appSettings";
import { type TimestampFormat } from "./clientSettings";
export function getTimestampFormatOptions(
timestampFormat: TimestampFormat,
-8
View File
@@ -357,10 +357,6 @@ describe("wsNativeApi", () => {
actionId: "action-1",
cwd: "/repo",
action: "commit",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
});
expect(requestMock).toHaveBeenCalledWith(
@@ -369,10 +365,6 @@ describe("wsNativeApi", () => {
actionId: "action-1",
cwd: "/repo",
action: "commit",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
},
{ timeoutMs: null },
);
-15
View File
@@ -74,19 +74,4 @@ describe("GitRunStackedActionInput", () => {
expect(parsed.actionId).toBe("action-1");
expect(parsed.action).toBe("commit");
});
it("accepts git text generation as a modelSelection", () => {
const parsed = decodeRunStackedActionInput({
actionId: "action-1",
cwd: "/repo",
action: "commit_push_pr",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
},
});
expect(parsed.modelSelection?.provider).toBe("claudeAgent");
expect(parsed.modelSelection?.model).toBe("claude-haiku-4-5");
});
});
-2
View File
@@ -1,6 +1,5 @@
import { Schema } from "effect";
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
import { ModelSelection } from "./orchestration";
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
@@ -80,7 +79,6 @@ export const GitRunStackedActionInput = Schema.Struct({
filePaths: Schema.optional(
Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),
),
modelSelection: ModelSelection,
});
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
+2 -2
View File
@@ -47,14 +47,14 @@ export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
export const CodexModelSelection = Schema.Struct({
provider: Schema.Literal("codex"),
model: TrimmedNonEmptyString,
options: Schema.optional(CodexModelOptions),
options: Schema.optionalKey(CodexModelOptions),
});
export type CodexModelSelection = typeof CodexModelSelection.Type;
export const ClaudeModelSelection = Schema.Struct({
provider: Schema.Literal("claudeAgent"),
model: TrimmedNonEmptyString,
options: Schema.optional(ClaudeModelOptions),
options: Schema.optionalKey(ClaudeModelOptions),
});
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
+53 -4
View File
@@ -1,8 +1,12 @@
import { Schema, Struct } from "effect";
import { Schema } from "effect";
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
import { EditorId } from "./editor";
import { DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER } from "./model";
import {
ClaudeModelOptions,
CodexModelOptions,
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
} from "./model";
import { ModelSelection, ProviderKind } from "./orchestration";
// ── Server Settings (server-authoritative) ───────────────────────────
@@ -39,13 +43,58 @@ export const ServerSettings = Schema.Struct({
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}),
}).pipe(Schema.withDecodingDefault(() => ({}))),
});
export type ServerSettings = typeof ServerSettings.Type;
export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeUnknownSync(ServerSettings)({});
export const ServerSettingsPatch = ServerSettings.mapFields(Struct.map(Schema.optionalKey));
const CodexModelOptionsPatch = Schema.Struct({
reasoningEffort: Schema.optionalKey(CodexModelOptions.fields.reasoningEffort),
fastMode: Schema.optionalKey(CodexModelOptions.fields.fastMode),
});
const ClaudeModelOptionsPatch = Schema.Struct({
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
});
const ModelSelectionPatch = Schema.Union([
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("codex")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(CodexModelOptionsPatch),
}),
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("claudeAgent")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(ClaudeModelOptionsPatch),
}),
]);
const CodexSettingsPatch = Schema.Struct({
binaryPath: Schema.optionalKey(Schema.String),
homePath: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const ClaudeSettingsPatch = Schema.Struct({
binaryPath: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
export const ServerSettingsPatch = Schema.Struct({
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
providers: Schema.optionalKey(
Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
}),
),
});
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
const KeybindingsMalformedConfigIssue = Schema.Struct({
+4
View File
@@ -31,6 +31,10 @@
"./schemaJson": {
"types": "./src/schemaJson.ts",
"import": "./src/schemaJson.ts"
},
"./Struct": {
"types": "./src/Struct.ts",
"import": "./src/Struct.ts"
}
},
"scripts": {
+25
View File
@@ -0,0 +1,25 @@
import * as P from "effect/Predicate";
export function deepMerge<T>(current: T, patch: unknown): T {
if (
!P.isObject(current) ||
!P.isObject(patch) ||
Array.isArray(current) ||
Array.isArray(patch)
) {
return patch as T;
}
const next = { ...current } as Record<string, unknown>;
for (const [key, value] of Object.entries(patch)) {
if (value === undefined) continue;
const existing = next[key];
next[key] =
P.isObject(existing) && P.isObject(value) && !Array.isArray(existing) && !Array.isArray(value)
? deepMerge(existing, value)
: value;
}
return next as T;
}
+63 -1
View File
@@ -1,4 +1,14 @@
import { Cause, Exit, Result, Schema, SchemaIssue } from "effect";
import {
Cause,
Effect,
Exit,
Option,
Result,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
} from "effect";
export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
schema: S,
@@ -32,3 +42,55 @@ export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
? SchemaIssue.makeFormatterDefault()(squashed.issue)
: Cause.pretty(cause);
};
/**
* A `Getter` that parses a lenient JSON string (tolerating trailing commas
* and JS-style comments) into an unknown value.
*
* Mirrors `SchemaGetter.parseJson()` but uses `parseLenientJson` instead
* of `JSON.parse`.
*/
const parseLenientJsonGetter = SchemaGetter.onSome((input: string) =>
Effect.try({
try: () => {
// Strip single-line comments — alternation preserves quoted strings.
let stripped = input.replace(
/("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g,
(match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
);
// Strip multi-line comments.
stripped = stripped.replace(
/("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g,
(match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
);
// Strip trailing commas before `}` or `]`.
stripped = stripped.replace(/,(\s*[}\]])/g, "$1");
return Option.some(JSON.parse(stripped));
},
catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: String(e) }),
}),
);
/**
* Schema transformation: lenient JSONC string ↔ unknown.
*
* Same API as `SchemaTransformation.fromJsonString`, but the decode side
* strips trailing commas and JS-style comments before parsing.
* Encoding produces strict JSON via `JSON.stringify`.
*/
export const fromLenientJsonString = new SchemaTransformation.Transformation(
parseLenientJsonGetter,
SchemaGetter.stringifyJson(),
);
/**
* Build a schema that decodes a lenient JSON string into `A`.
*
* Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates
* trailing commas and comments in the input.
*/
export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));