Compare commits

...
Author SHA1 Message Date
Julius Marminge 95144d8d18 Await hydrated client settings for new thread creation 2026-06-19 11:24:33 -07:00
JustMarkDevandcodex 31078cb4e0 Add configurable default access mode for new threads
- Persist client-side default runtime mode in settings
- Use it when creating draft threads and new local threads
- Surface the setting in the UI and cover it with tests

Co-authored-by: codex <[email protected]>
2026-06-19 11:21:26 -07:00
11 changed files with 256 additions and 22 deletions

No files matched your search

@@ -15,6 +15,7 @@ const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
defaultRuntimeMode: "full-access",
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
+13 -5
View File
@@ -89,7 +89,6 @@ import {
} from "../proposedPlan";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
DEFAULT_THREAD_TERMINAL_ID,
MAX_TERMINALS_PER_GROUP,
type ChatMessage,
@@ -141,7 +140,11 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
buildNewDraftExecutionDefaults,
resolveNewDraftStartFromOrigin,
} from "../lib/chatThreadActions";
import { loadClientSettingsForNewThread } from "../lib/clientSettingsHydration";
import {
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
@@ -1212,7 +1215,8 @@ function ChatViewContent(props: ChatViewProps) {
const threadError = isServerThread
? (localServerError ?? serverThread?.session?.lastError ?? null)
: localDraftError;
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const runtimeMode =
composerRuntimeMode ?? activeThread?.runtimeMode ?? settings.defaultRuntimeMode;
const interactionMode =
composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
@@ -1526,13 +1530,17 @@ function ChatViewContent(props: ChatViewProps) {
return activeDraftSession.threadId;
}
const clientSettings = await loadClientSettingsForNewThread();
if (!clientSettings) {
return null;
}
const nextDraftId = newDraftId();
const nextThreadId = newThreadId();
setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, {
threadId: nextThreadId,
createdAt: new Date().toISOString(),
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
...buildNewDraftExecutionDefaults(clientSettings.defaultRuntimeMode),
...input,
});
await navigate({
@@ -9,6 +9,7 @@ import {
ProviderDriverKind,
type ProviderInstanceConfig,
type ProviderInstanceId,
type RuntimeMode,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
@@ -108,6 +109,12 @@ const TIMESTAMP_FORMAT_LABELS = {
"24-hour": "24-hour",
} as const;
const RUNTIME_MODE_LABELS: Record<RuntimeMode, string> = {
"approval-required": "Supervised",
"auto-accept-edits": "Auto-accept edits",
"full-access": "Full access",
};
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
function withoutProviderInstanceKey<V>(
@@ -412,6 +419,9 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin
? ["New worktrees start from origin"]
: []),
...(settings.defaultRuntimeMode !== DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode
? ["Default access mode"]
: []),
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
? ["Add project base directory"]
: []),
@@ -429,6 +439,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.addProjectBaseDirectory,
settings.defaultRuntimeMode,
settings.defaultThreadEnvMode,
settings.newWorktreesStartFromOrigin,
settings.diffIgnoreWhitespace,
@@ -462,6 +473,7 @@ export function useSettingsRestore(onRestored?: () => void) {
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
defaultRuntimeMode: DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode,
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
@@ -797,6 +809,52 @@ export function GeneralSettingsPanel() {
/>
) : null}
<SettingsRow
title="Default access"
description="Pick the permission mode used when newly created draft threads start."
resetAction={
settings.defaultRuntimeMode !== DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode ? (
<SettingResetButton
label="default access mode"
onClick={() =>
updateSettings({
defaultRuntimeMode: DEFAULT_UNIFIED_SETTINGS.defaultRuntimeMode,
})
}
/>
) : null
}
control={
<Select
value={settings.defaultRuntimeMode}
onValueChange={(value) => {
if (
value === "approval-required" ||
value === "auto-accept-edits" ||
value === "full-access"
) {
updateSettings({ defaultRuntimeMode: value });
}
}}
>
<SelectTrigger className="w-full sm:w-44" aria-label="Default access mode">
<SelectValue>{RUNTIME_MODE_LABELS[settings.defaultRuntimeMode]}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="approval-required">
{RUNTIME_MODE_LABELS["approval-required"]}
</SelectItem>
<SelectItem hideIndicator value="auto-accept-edits">
{RUNTIME_MODE_LABELS["auto-accept-edits"]}
</SelectItem>
<SelectItem hideIndicator value="full-access">
{RUNTIME_MODE_LABELS["full-access"]}
</SelectItem>
</SelectPopup>
</Select>
}
/>
<SettingsRow
title="Add project starts in"
description='Leave empty to use "~/" when the Add Project browser opens.'
+16 -7
View File
@@ -3,7 +3,7 @@ import {
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
import { type ScopedProjectRef } from "@t3tools/contracts";
import { useParams, useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import {
@@ -20,7 +20,11 @@ import {
selectProjectGroupingSettings,
} from "../logicalProject";
import { readThreadShell, useProjects, useThread } from "../state/entities";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
buildNewDraftExecutionDefaults,
resolveNewDraftStartFromOrigin,
} from "../lib/chatThreadActions";
import { loadClientSettingsForNewThread } from "../lib/clientSettingsHydration";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
@@ -152,11 +156,16 @@ export function useNewThreadHandler() {
return Promise.resolve();
}
const draftId = newDraftId();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const initialEnvMode = options?.envMode ?? "local";
return (async () => {
const clientSettings = await loadClientSettingsForNewThread();
if (!clientSettings) {
return;
}
const draftId = newDraftId();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const initialEnvMode = options?.envMode ?? "local";
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
threadId,
createdAt,
@@ -169,7 +178,7 @@ export function useNewThreadHandler() {
envMode: initialEnvMode,
newWorktreesStartFromOrigin,
}),
runtimeMode: DEFAULT_RUNTIME_MODE,
...buildNewDraftExecutionDefaults(clientSettings.defaultRuntimeMode),
});
applyStickyState(draftId);
+74
View File
@@ -0,0 +1,74 @@
import { DEFAULT_CLIENT_SETTINGS, type DesktopBridge } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, reject, resolve };
}
function stubDesktopSettings(getClientSettings: DesktopBridge["getClientSettings"]): void {
vi.stubGlobal("window", {
desktopBridge: {
getClientSettings,
} as DesktopBridge,
});
}
afterEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("getHydratedClientSettings", () => {
it("waits for persisted settings instead of returning the eager defaults", async () => {
const persistedSettings = {
...DEFAULT_CLIENT_SETTINGS,
defaultRuntimeMode: "approval-required" as const,
};
const settingsRequest = deferred<typeof persistedSettings | null>();
stubDesktopSettings(() => settingsRequest.promise);
const { getHydratedClientSettings } = await import("./useSettings");
let settled = false;
const hydration = getHydratedClientSettings().then((settings) => {
settled = true;
return settings;
});
await Promise.resolve();
expect(settled).toBe(false);
settingsRequest.resolve(persistedSettings);
await expect(hydration).resolves.toEqual(persistedSettings);
});
it("rejects when persisted settings cannot be loaded", async () => {
const error = new Error("settings unavailable");
stubDesktopSettings(() => Promise.reject(error));
vi.spyOn(console, "error").mockImplementation(() => undefined);
const { getHydratedClientSettings } = await import("./useSettings");
await expect(getHydratedClientSettings()).rejects.toBe(error);
});
it("blocks new-thread defaults when persisted settings cannot be loaded", async () => {
const error = new Error("settings unavailable");
stubDesktopSettings(() => Promise.reject(error));
vi.spyOn(console, "error").mockImplementation(() => undefined);
const { toastManager } = await import("../components/ui/toast");
const addToast = vi.spyOn(toastManager, "add").mockImplementation(() => "toast-1");
const { loadClientSettingsForNewThread } = await import("../lib/clientSettingsHydration");
await expect(loadClientSettingsForNewThread()).resolves.toBeNull();
expect(addToast).toHaveBeenCalledWith(
expect.objectContaining({
title: "Could not create thread",
}),
);
});
});
+16 -6
View File
@@ -64,7 +64,7 @@ function setClientSettingsHydrated(nextHydrated: boolean): void {
function subscribeClientSettings(listener: () => void): () => void {
clientSettingsListeners.add(listener);
void hydrateClientSettings();
void hydrateClientSettings().catch(() => undefined);
return () => {
clientSettingsListeners.delete(listener);
};
@@ -76,7 +76,7 @@ function getClientSettingsHydratedSnapshot(): boolean {
function subscribeClientSettingsHydration(listener: () => void): () => void {
clientSettingsHydrationListeners.add(listener);
void hydrateClientSettings();
void hydrateClientSettings().catch(() => undefined);
return () => {
clientSettingsHydrationListeners.delete(listener);
};
@@ -100,12 +100,10 @@ async function hydrateClientSettings(): Promise<void> {
if (persistedSettings) {
replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
}
setClientSettingsHydrated(true);
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
} finally {
if (hydrationGeneration === clientSettingsHydrationGeneration) {
setClientSettingsHydrated(true);
}
throw error;
}
})();
@@ -167,6 +165,18 @@ export function getClientSettings(): ClientSettings {
return getClientSettingsSnapshot();
}
/**
* Waits for persisted client settings before returning the current snapshot.
*
* User actions whose behavior depends on a persisted setting must use this
* accessor instead of the eager default snapshot. Hydration failures reject
* so callers can stop the action instead of silently falling back.
*/
export async function getHydratedClientSettings(): Promise<ClientSettings> {
await hydrateClientSettings();
return getClientSettingsSnapshot();
}
export function useClientSettingsHydrated(): boolean {
return useSyncExternalStore(
subscribeClientSettingsHydration,
+9 -1
View File
@@ -2,8 +2,9 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import {
resolveThreadActionProjectRef,
buildNewDraftExecutionDefaults,
resolveNewDraftStartFromOrigin,
resolveThreadActionProjectRef,
startNewLocalThreadFromContext,
startNewThreadFromContext,
type ChatThreadActionContext,
@@ -25,6 +26,13 @@ function createContext(overrides: Partial<ChatThreadActionContext> = {}): ChatTh
}
describe("chatThreadActions", () => {
it("initializes new drafts with the configured default access mode", () => {
expect(buildNewDraftExecutionDefaults("approval-required")).toEqual({
runtimeMode: "approval-required",
interactionMode: "default",
});
});
it("only applies the start-from-origin default to new worktree drafts", () => {
expect(
resolveNewDraftStartFromOrigin({
+18 -1
View File
@@ -1,5 +1,12 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentId, ProjectId, ScopedProjectRef } from "@t3tools/contracts";
import {
DEFAULT_PROVIDER_INTERACTION_MODE,
type EnvironmentId,
type ProjectId,
type ProviderInteractionMode,
type RuntimeMode,
type ScopedProjectRef,
} from "@t3tools/contracts";
import type { DraftThreadEnvMode } from "../composerDraftStore";
interface ThreadContextLike {
@@ -43,6 +50,16 @@ export function resolveNewDraftStartFromOrigin(input: {
return input.envMode === "worktree" && input.newWorktreesStartFromOrigin;
}
export function buildNewDraftExecutionDefaults(defaultRuntimeMode: RuntimeMode): {
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
} {
return {
runtimeMode: defaultRuntimeMode,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
};
}
export function resolveThreadActionProjectRef(
context: ChatThreadActionContext,
): ScopedProjectRef | null {
@@ -0,0 +1,22 @@
import type { ClientSettings } from "@t3tools/contracts/settings";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { getHydratedClientSettings } from "../hooks/useSettings";
export async function loadClientSettingsForNewThread(): Promise<ClientSettings | null> {
try {
return await getHydratedClientSettings();
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not create thread",
description:
error instanceof Error
? `Could not load your saved default access mode. ${error.message}`
: "Could not load your saved default access mode. No thread was created.",
}),
);
return null;
}
}
+24 -1
View File
@@ -1,13 +1,36 @@
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { DEFAULT_RUNTIME_MODE } from "./orchestration.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "./settings.ts";
import {
ClientSettingsPatch,
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_SERVER_SETTINGS,
ServerSettings,
ServerSettingsPatch,
} from "./settings.ts";
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
describe("ClientSettings default runtime mode", () => {
it("defaults new thread access mode to the existing runtime default", () => {
expect(DEFAULT_CLIENT_SETTINGS.defaultRuntimeMode).toBe(DEFAULT_RUNTIME_MODE);
expect(decodeClientSettings({}).defaultRuntimeMode).toBe(DEFAULT_RUNTIME_MODE);
});
it("accepts runtime mode patches", () => {
const patch = decodeClientSettingsPatch({ defaultRuntimeMode: "approval-required" });
expect(patch.defaultRuntimeMode).toBe("approval-required");
});
});
describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
it("defaults to an empty record so legacy configs without the key still decode", () => {
expect(DEFAULT_SERVER_SETTINGS.providerInstances).toEqual({});
+5 -1
View File
@@ -4,7 +4,7 @@ import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
import { ModelSelection } from "./orchestration.ts";
import { DEFAULT_RUNTIME_MODE, ModelSelection, RuntimeMode } from "./orchestration.ts";
import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts";
// ── Client Settings (local-only) ───────────────────────────────
@@ -43,6 +43,9 @@ export const ClientSettingsSchema = Schema.Struct({
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
defaultRuntimeMode: RuntimeMode.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE)),
),
dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
),
@@ -516,6 +519,7 @@ export const ClientSettingsPatch = Schema.Struct({
autoOpenPlanSidebar: Schema.optionalKey(Schema.Boolean),
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
defaultRuntimeMode: Schema.optionalKey(RuntimeMode),
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
diffWordWrap: Schema.optionalKey(Schema.Boolean),
favorites: Schema.optionalKey(