Skip to content
TypeScript

feat(settings): add shared project defaults and scoped overrides (#9754)

maria9f40b2f563c6
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index df9486e8556..f63a206e7ef 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -7,12 +7,21 @@ import {
} from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
-import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
+import {
+ DEFAULT_SERVER_SETTINGS,
+ EnvironmentId,
+ ThreadId,
+ type ProjectScript,
+} from "@t3tools/contracts";
import {
requestOlderThreadTurns,
threadHasOlderTurns,
} from "@t3tools/client-runtime/state/threads";
-import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
+import {
+ projectScriptCwd,
+ projectScriptRuntimeEnv,
+ resolveProjectScripts,
+} from "@t3tools/shared/projectScripts";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useWorkspaceState } from "../../state/workspace";
@@ -627,7 +636,12 @@ function ThreadRouteContent(
gitOperationLabel: gitState.gitOperationLabel,
canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
- projectScripts: selectedThreadProject?.scripts ?? [],
+ projectScripts: selectedThreadProject
+ ? resolveProjectScripts(
+ routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
+ selectedThreadProject,
+ )
+ : [],
terminalSessions: terminalMenuSessions,
showDirectFileControl: layout.usesSplitView,
onOpenTerminal: handleOpenTerminal,
@@ -819,6 +833,7 @@ function ThreadRouteContent(
<>
{activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
<NativeStackScreenOptions
+ optionsVersion={threadGitControlProps.projectScripts}
options={{
// Android draws its own in-flow header (AndroidScreenHeader below);
// the native stack header stays iOS-only.
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index c17e2c002a1..4020c1de941 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -427,7 +427,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const projectDefaultModelSelection = resolveDefaultableModelSelection(
selectedEnvironmentServerConfig,
- selectedProject?.defaultModelSelection ?? null,
+ selectedProject?.defaultModelSelection ??
+ selectedEnvironmentServerConfig?.settings.defaultModelSelection ??
+ null,
);
const storedStickyModelSelection = useStickyComposerModelSelection();
const stickyModelSelection = resolveDefaultableModelSelection(
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
index 6cc399dd4de..225458d7142 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
@@ -6,6 +6,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as TerminalManager from "../terminal/Manager.ts";
import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
@@ -68,13 +69,73 @@ const makeTerminalManagerLayer = (
const testLayer = (
project: OrchestrationProject,
terminal: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
+ settings = ServerSettings.layerTest(),
) =>
ProjectSetupScriptRunner.layer.pipe(
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
Layer.provideMerge(makeTerminalManagerLayer(terminal)),
+ Layer.provide(settings),
);
describe("ProjectSetupScriptRunner", () => {
+ it.effect("runs the inherited machine setup action in the checkout's worktree", () => {
+ const open = vi.fn(() =>
+ Effect.succeed({
+ threadId: "thread-1",
+ terminalId: "setup-default-setup",
+ cwd: "/repo/worktrees/a",
+ worktreePath: "/repo/worktrees/a",
+ status: "running" as const,
+ pid: 123,
+ history: "",
+ exitCode: null,
+ exitSignal: null,
+ label: "setup-default-setup",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ }),
+ );
+ const write = vi.fn(() => Effect.void);
+ return Effect.gen(function* () {
+ const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
+ const result = yield* runner.runForThread({
+ threadId: "thread-1",
+ projectId: "project-1",
+ worktreePath: "/repo/worktrees/a",
+ });
+ expect(result).toMatchObject({ status: "started", scriptId: "default-setup" });
+ expect(open).toHaveBeenCalledWith({
+ threadId: "thread-1",
+ terminalId: "setup-default-setup",
+ cwd: "/repo/worktrees/a",
+ worktreePath: "/repo/worktrees/a",
+ env: { T3CODE_PROJECT_ROOT: "/repo/project", T3CODE_WORKTREE_PATH: "/repo/worktrees/a" },
+ });
+ expect(write).toHaveBeenCalledWith({
+ threadId: "thread-1",
+ terminalId: "setup-default-setup",
+ data: "npm install\r",
+ });
+ }).pipe(
+ Effect.provide(
+ testLayer(
+ makeProject([]),
+ { open, write },
+ ServerSettings.layerTest({
+ defaultProjectScripts: [
+ {
+ id: "default-setup",
+ name: "Setup",
+ command: "npm install",
+ icon: "configure",
+ runOnWorktreeCreate: true,
+ },
+ ],
+ }),
+ ),
+ ),
+ );
+ });
+
it.effect("returns no-script when no setup script exists", () => {
const open = vi.fn(() => Effect.die("unexpected open"));
const write = vi.fn(() => Effect.die("unexpected write"));
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts
index 41bf0fabf48..6a79c853dc9 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts
@@ -1,5 +1,9 @@
import { ProjectId } from "@t3tools/contracts";
-import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
+import {
+ projectScriptRuntimeEnv,
+ resolveProjectScripts,
+ setupProjectScript,
+} from "@t3tools/shared/projectScripts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -7,6 +11,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as TerminalManager from "../terminal/Manager.ts";
export interface ProjectSetupScriptRunnerResultNoScript {
@@ -40,7 +45,7 @@ export class ProjectSetupScriptOperationError extends Schema.TaggedErrorClass<Pr
projectId: Schema.optional(Schema.String),
projectCwd: Schema.optional(Schema.String),
worktreePath: Schema.String,
- operation: Schema.Literals(["resolveProject", "openTerminal", "writeCommand"]),
+ operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal", "writeCommand"]),
cause: Schema.Defect(),
},
) {
@@ -81,6 +86,7 @@ export class ProjectSetupScriptRunner extends Context.Service<
export const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const terminalManager = yield* TerminalManager.TerminalManager;
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
"ProjectSetupScriptRunner.runForThread",
@@ -124,7 +130,17 @@ export const make = Effect.gen(function* () {
return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);
}
- const script = setupProjectScript(project.scripts);
+ const settings = yield* serverSettings.getSettings.pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProjectSetupScriptOperationError({
+ ...errorContext,
+ operation: "readSettings",
+ cause,
+ }),
+ ),
+ );
+ const script = setupProjectScript(resolveProjectScripts(settings, project));
if (!script) {
return {
status: "no-script",
diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts
index 238265ec5a4..fecd7fca909 100644
--- a/apps/server/src/provider/Layers/ProviderService.test.ts
+++ b/apps/server/src/provider/Layers/ProviderService.test.ts
@@ -19,6 +19,8 @@ import {
EnvironmentId,
EventId,
MessageId,
+ OrchestrationThreadShell,
+ ProjectId,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
ProviderDriverKind,
ProviderInstanceId,
@@ -75,6 +77,7 @@ import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
+import * as ProjectionSnapshotQuery from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
const serverConfigTestLayer = ServerConfig.layerTest(process.cwd(), process.cwd()).pipe(
@@ -4302,10 +4305,17 @@ boundedListing.layer("ProviderServiceLive session listing", (it) => {
);
});
+const decodeBrowserAccessThreadShell = Schema.decodeUnknownEffect(OrchestrationThreadShell);
+
describe("agent browser access", () => {
const revokedThreads: Array<ThreadId> = [];
+ const projectId = ProjectId.make("project-browser-access");
- const startSessionWith = (enableAgentBrowserAccess: boolean, threadId: ThreadId) =>
+ const startSessionWith = (
+ enableAgentBrowserAccess: boolean,
+ threadId: ThreadId,
+ projectOverride?: boolean,
+ ) =>
Effect.gen(function* () {
const issued: Array<ThreadId> = [];
const codex = makeFakeCodexAdapter();
@@ -4319,6 +4329,49 @@ describe("agent browser access", () => {
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
+ const projectionLayer = Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
+ getImportedAgentSessionSources: () => Effect.die("unused"),
+ getUserInputActivity: () => Effect.die("unused"),
+ getCommandReadModel: () => Effect.die("unused"),
+ getSnapshot: () => Effect.die("unused"),
+ getShellSnapshot: () => Effect.die("unused"),
+ getArchivedShellSnapshot: () => Effect.die("unused"),
+ getSnapshotSequence: () => Effect.die("unused"),
+ getCounts: () => Effect.die("unused"),
+ getEventReplayStats: () => Effect.die("unused"),
+ getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
+ getProjectShellById: () => Effect.die("unused"),
+ getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
+ getThreadCheckpointContext: () => Effect.die("unused"),
+ getFullThreadDiffContext: () => Effect.die("unused"),
+ getThreadRuntimeContext: () => Effect.die("unused"),
+ getThreadShellById: (requestedThreadId) =>
+ Effect.gen(function* () {
+ assert.equal(requestedThreadId, threadId);
+ return Option.some(
+ yield* decodeBrowserAccessThreadShell({
+ id: threadId,
+ projectId,
+ title: "Browser access test",
+ modelSelection: createModelSelection(codexInstanceId, "gpt-5.4"),
+ runtimeMode: "full-access",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ session: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+ }),
+ );
+ }).pipe(Effect.orDie),
+ getThreadDetailById: () => Effect.die("unused"),
+ getThreadDetailSnapshot: () => Effect.die("unused"),
+ searchThreads: () => Effect.die("unused"),
+ });
const providerLayer = makeProviderServiceLive({
issueMcpCredential: (request) =>
Effect.sync(() => {
@@ -4329,7 +4382,14 @@ describe("agent browser access", () => {
}).pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
- Layer.provide(ServerSettings.ServerSettingsService.layerTest({ enableAgentBrowserAccess })),
+ Layer.provide(projectionLayer),
+ Layer.provide(
+ ServerSettings.ServerSettingsService.layerTest({
+ enableAgentBrowserAccess,
+ projectAgentBrowserAccessOverrides:
+ projectOverride === undefined ? {} : { [projectId]: projectOverride },
+ }),
+ ),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
@@ -4387,4 +4447,22 @@ describe("agent browser access", () => {
assert.deepEqual(issued, [threadId]);
}).pipe(Effect.provide(NodeServices.layer)),
);
+
+ it.effect("withholds and revokes MCP credentials when the project disables browser access", () =>
+ Effect.gen(function* () {
+ const threadId = asThreadId("thread-project-browser-off");
+ revokedThreads.length = 0;
+ const issued = yield* startSessionWith(true, threadId, false);
+ assert.deepEqual(issued, []);
+ assert.deepEqual(revokedThreads, [threadId]);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("requests an MCP credential when the project overrides browser access to on", () =>
+ Effect.gen(function* () {
+ const threadId = asThreadId("thread-project-browser-on");
+ const issued = yield* startSessionWith(false, threadId, true);
+ assert.deepEqual(issued, [threadId]);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
});
diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts
index b853d779763..d9cac46ec4d 100644
--- a/apps/server/src/provider/Layers/ProviderService.ts
+++ b/apps/server/src/provider/Layers/ProviderService.ts
@@ -32,6 +32,7 @@ import {
import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations";
import { causeErrorTag } from "@t3tools/shared/observability";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
+import { resolveProjectAgentBrowserAccess } from "@t3tools/shared/serverSettings";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -72,6 +73,7 @@ import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
import * as ServerSettings from "../../serverSettings.ts";
+import * as ProjectionSnapshotQuery from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
const isModelSelection = Schema.is(ModelSelection);
interface PendingCompaction {
@@ -323,6 +325,9 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const serverSettings = yield* ServerSettings.ServerSettingsService;
+ const projectionQuery = yield* Effect.serviceOption(
+ ProjectionSnapshotQuery.ProjectionSnapshotQuery,
+ );
const issueMcpCredential =
options?.issueMcpCredential ?? McpSessionRegistry.issueActiveMcpCredential;
const revokeMcpCredential =
@@ -714,8 +719,19 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
* "off" silently becoming "on" would violate the user's stated choice,
* whereas the reverse costs an agent one toolset and is visible immediately.
*/
- const agentBrowserAccessEnabled = serverSettings.getSettings.pipe(
- Effect.map((settings) => settings.enableAgentBrowserAccess),
+ const agentBrowserAccessEnabled = Effect.fn("ProviderService.agentBrowserAccessEnabled")(
+ function* (threadId: ThreadId) {
+ const settings = yield* serverSettings.getSettings;
+ if (Object.keys(settings.projectAgentBrowserAccessOverrides).length === 0) {
+ return settings.enableAgentBrowserAccess;
+ }
+ // Provider-only runtimes may omit orchestration. An unresolved project
+ // must not bypass an explicit browser override.
+ if (Option.isNone(projectionQuery)) return false;
+ const thread = yield* projectionQuery.value.getThreadShellById(threadId);
+ if (Option.isNone(thread)) return false;
+ return resolveProjectAgentBrowserAccess(settings, thread.value.projectId);
+ },
Effect.catch((cause) =>
Effect.logWarning(
"Could not read server settings; withholding agent browser access for this session.",
@@ -726,7 +742,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
Effect.gen(function* () {
- if (!(yield* agentBrowserAccessEnabled)) {
+ if (!(yield* agentBrowserAccessEnabled(threadId))) {
// Revoke as well as clear. Every other prepare path reaches
// `issueActiveMcpCredential`, which revokes the thread first, so
// skipping it here would leave a previously issued bearer token valid
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index c0be0c44457..4abe43d8a63 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -317,7 +317,7 @@ const PullRequestServiceLive = PullRequestService.layer.pipe(
);
const GitManagerLayerLive = GitManager.layer.pipe(
- Layer.provideMerge(ProjectSetupScriptRunner.layer),
+ Layer.provideMerge(ProjectSetupScriptRunner.layer.pipe(Layer.provide(ServerSettingsLayerLive))),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
Layer.provideMerge(TextGeneration.layer),
@@ -353,7 +353,9 @@ const VcsLayerLive = Layer.empty.pipe(
Layer.provideMerge(
VcsStatusBroadcaster.layer.pipe(
Layer.provide(GitWorkflowLayerLive),
- Layer.provide(VcsStatusBroadcaster.autoPullPolicyLayer),
+ Layer.provide(
+ VcsStatusBroadcaster.autoPullPolicyLayer.pipe(Layer.provide(ServerSettingsLayerLive)),
+ ),
),
),
);
diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts
index 8cba5255227..88e3c2e8858 100644
--- a/apps/server/src/serverRuntimeStartup.test.ts
+++ b/apps/server/src/serverRuntimeStartup.test.ts
@@ -14,6 +14,7 @@ import * as ServerConfig from "./config.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
+import * as ServerSettings from "./serverSettings.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () =>
@@ -40,7 +41,7 @@ it.effect("automatic pull only updates enabled, behind, clean default-branch che
}),
} as unknown as GitVcsDriver.GitVcsDriver["Service"];
const project = (workspaceRoot: string, autoPull = true) =>
- ({ workspaceRoot, autoPull }) as never;
+ ({ id: ProjectId.make(workspaceRoot), workspaceRoot, autoPull }) as never;
yield* ServerRuntimeStartup.autoPullProjects([
project("/clean"),
@@ -52,6 +53,16 @@ it.effect("automatic pull only updates enabled, behind, clean default-branch che
]).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
assert.deepStrictEqual(pulled, ["/clean"]);
+
+ pulled.length = 0;
+ yield* ServerRuntimeStartup.autoPullProjects(
+ [project("/inherited", false), project("/opted-out"), project("/dirty", false)],
+ {
+ defaultAutoPull: true,
+ projectAutoPullOverrides: { [ProjectId.make("/opted-out")]: false },
+ },
+ ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
+ assert.deepStrictEqual(pulled, ["/inherited"]);
}),
);
@@ -124,6 +135,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
return Effect.gen(function* () {
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
+ Effect.provide(ServerSettings.layerTest()),
Effect.provideService(ServerConfig.ServerConfig, {
cwd: "/tmp/startup-project",
autoBootstrapProjectFromCwd: true,
@@ -189,8 +201,19 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
});
});
-it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when missing", () =>
+it.effect.each([
+ { existing: false, machineModel: null, projectModel: null },
+ { existing: false, machineModel: "claude-sonnet-4-6", projectModel: null },
+ { existing: true, machineModel: "claude-sonnet-4-6", projectModel: null },
+ { existing: true, machineModel: "claude-sonnet-4-6", projectModel: "gpt-5.4" },
+])("auto-bootstrap model precedence: %j", ({ existing, machineModel, projectModel }) =>
Effect.gen(function* () {
+ const machineSelection = machineModel
+ ? { instanceId: ProviderInstanceId.make("claude-code"), model: machineModel }
+ : null;
+ const projectSelection = projectModel
+ ? { instanceId: ProviderInstanceId.make("codex"), model: projectModel }
+ : null;
const dispatchCalls = yield* Ref.make<
ReadonlyArray<{
readonly type: string;
@@ -199,6 +222,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
}>
>([]);
const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
+ Effect.provide(ServerSettings.layerTest({ defaultModelSelection: machineSelection })),
Effect.provideService(ServerConfig.ServerConfig, {
cwd: "/tmp/startup-project",
autoBootstrapProjectFromCwd: true,
@@ -212,7 +236,21 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getEventReplayStats: () => Effect.die("unused"),
- getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
+ getActiveProjectByWorkspaceRoot: () =>
+ Effect.succeed(
+ existing
+ ? Option.some({
+ id: ProjectId.make("existing-project"),
+ title: "Startup Project",
+ workspaceRoot: "/tmp/startup-project",
+ defaultModelSelection: projectSelection,
+ scripts: [],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ deletedAt: null,
+ })
+ : Option.none(),
+ ),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getImportedAgentSessionSources: () => Effect.die("unused"),
@@ -241,18 +279,22 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
assert.equal(typeof targets.bootstrapProjectId, "string");
assert.equal(typeof targets.bootstrapThreadId, "string");
- assert.equal(targets.bootstrapProjectCreated, true);
+ assert.equal(targets.bootstrapProjectCreated, !existing);
assert.equal(targets.bootstrapThreadCreated, true);
const commands = yield* Ref.get(dispatchCalls);
assert.deepStrictEqual(
commands.map((command) => command.type),
- ["project.create", "thread.create"],
+ existing ? ["thread.create"] : ["project.create", "thread.create"],
+ );
+ if (!existing) assert.equal("defaultModelSelection" in commands[0]!, false);
+ assert.deepStrictEqual(
+ commands.at(-1)?.modelSelection,
+ projectSelection ??
+ machineSelection ?? {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: DEFAULT_MODEL,
+ },
);
- assert.equal("defaultModelSelection" in commands[0]!, false);
- assert.deepStrictEqual(commands[1]?.modelSelection, {
- instanceId: ProviderInstanceId.make("codex"),
- model: DEFAULT_MODEL,
- });
}),
);
@@ -262,6 +304,7 @@ it.effect(
Effect.gen(function* () {
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
+ Effect.provide(ServerSettings.layerTest()),
Effect.provideService(ServerConfig.ServerConfig, {
cwd: "/tmp/startup-project",
autoBootstrapProjectFromCwd: true,
@@ -322,6 +365,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
const error = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
+ Effect.provide(ServerSettings.layerTest()),
Effect.provideService(ServerConfig.ServerConfig, {
cwd: "/tmp/startup-project",
autoBootstrapProjectFromCwd: true,
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index 2a12dbb3637..6f8bbc053b0 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -2,6 +2,7 @@ import {
CommandId,
DEFAULT_MODEL,
DEFAULT_PROVIDER_INTERACTION_MODE,
+ DEFAULT_SERVER_SETTINGS,
type ModelSelection,
type OrchestrationProjectShell,
ProjectId,
@@ -9,6 +10,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
+import { resolveProjectAutoPull } from "@t3tools/shared/serverSettings";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
@@ -198,6 +200,9 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
let bootstrapThreadCreated = false;
if (serverConfig.autoBootstrapProjectFromCwd) {
+ const settings = yield* (yield* ServerSettings.ServerSettingsService).getSettings;
+ const defaultModelSelection =
+ settings.defaultModelSelection ?? getAutoBootstrapThreadModelSelection();
yield* Effect.gen(function* () {
const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
serverConfig.cwd,
@@ -209,7 +214,7 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
const createdAt = DateTime.formatIso(yield* DateTime.now);
nextProjectId = ProjectId.make(yield* randomUUID);
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
- nextThreadModelSelection = getAutoBootstrapThreadModelSelection();
+ nextThreadModelSelection = defaultModelSelection;
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.make(yield* randomUUID),
@@ -224,7 +229,7 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
nextProjectId = existingProject.value.id;
bootstrapProjectId = nextProjectId;
nextThreadModelSelection =
- existingProject.value.defaultModelSelection ?? getAutoBootstrapThreadModelSelection();
+ existingProject.value.defaultModelSelection ?? defaultModelSelection;
}
yield* Effect.gen(function* () {
@@ -737,12 +742,16 @@ interface StartupOptions {
export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
projects: ReadonlyArray<OrchestrationProjectShell>,
+ settings: Pick<
+ typeof DEFAULT_SERVER_SETTINGS,
+ "defaultAutoPull" | "projectAutoPullOverrides"
+ > = DEFAULT_SERVER_SETTINGS,
) {
const git = yield* GitVcsDriver.GitVcsDriver;
const workspaceRoots = [
...new Set(
projects
- .filter((project) => project.autoPull === true)
+ .filter((project) => resolveProjectAutoPull(settings, project.id, project.autoPull))
.map((project) => project.workspaceRoot),
),
];
@@ -813,7 +822,11 @@ export const make = (options?: StartupOptions) =>
const reactorScope = yield* Scope.make("sequential");
const syncAutoPullProjects = projectionSnapshotQuery.getShellSnapshot().pipe(
- Effect.flatMap((snapshot) => autoPullProjects(snapshot.projects)),
+ Effect.flatMap((snapshot) =>
+ serverSettings.getSettings.pipe(
+ Effect.flatMap((settings) => autoPullProjects(snapshot.projects, settings)),
+ ),
+ ),
Effect.catch((cause) =>
Effect.logWarning("Failed to load projects for automatic pull", { cause }),
),
diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts
index 04d320c03bf..c00a07f2a7a 100644
--- a/apps/server/src/vcs/VcsStatusBroadcaster.ts
+++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts
@@ -22,10 +22,12 @@ import type {
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
+import { resolveProjectAutoPull } from "@t3tools/shared/serverSettings";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import * as ServerSettings from "../serverSettings.ts";
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
@@ -151,12 +153,17 @@ export const autoPullPolicyLayer = Layer.effect(
VcsAutoPullPolicy,
Effect.gen(function* () {
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
return {
- isEnabled: (cwd: string) =>
- snapshots.getActiveProjectByWorkspaceRoot(cwd).pipe(
- Effect.map((project) => project._tag === "Some" && project.value.autoPull === true),
- Effect.orElseSucceed(() => false),
- ),
+ isEnabled: Effect.fn("VcsAutoPullPolicy.isEnabled")(
+ function* (cwd: string) {
+ const project = yield* snapshots.getActiveProjectByWorkspaceRoot(cwd);
+ if (project._tag === "None") return false;
+ const settings = yield* serverSettings.getSettings;
+ return resolveProjectAutoPull(settings, project.value.id, project.value.autoPull);
+ },
+ Effect.orElseSucceed(() => false),
+ ),
};
}),
);
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index c9c2c60badb..d9d66df9cd5 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -53,7 +53,11 @@ import {
createModelSelection,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
-import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
+import {
+ projectScriptCwd,
+ projectScriptRuntimeEnv,
+ resolveProjectScripts,
+} from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
import {
@@ -276,7 +280,6 @@ import { appendReviewCommentsToPrompt, type ReviewCommentContext } from "../revi
import { environmentCatalog } from "../connection/catalog";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
-import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import {
environmentServerConfigsAtom,
@@ -1386,7 +1389,9 @@ export default function ChatView(props: ChatViewProps) {
[environmentId, threadId],
);
const routeThreadKey = useMemo(() => scopedThreadKey(routeThreadRef), [routeThreadRef]);
- const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });
+ const updateProjectScriptSettings = useAtomCommand(serverEnvironment.updateSettings, {
+ reportFailure: false,
+ });
const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
reportFailure: false,
});
@@ -1474,9 +1479,6 @@ export default function ChatView(props: ChatViewProps) {
}, [routeKind, routeThreadRef, routeThreadState]);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const settings = useEnvironmentSettings(environmentId);
- // New-thread defaults live in the primary environment's settings.json (the
- // settings UI never writes to remote environments), so read them from the
- // primary server rather than the thread's environment.
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
@@ -1758,10 +1760,17 @@ export default function ChatView(props: ChatViewProps) {
? buildLocalDraftThread(
threadId,
draftThread,
- fallbackDraftProject?.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,
+ fallbackDraftProject?.defaultModelSelection ??
+ settings.defaultModelSelection ??
+ NO_PROVIDER_MODEL_SELECTION,
)
: undefined,
- [draftThread, fallbackDraftProject?.defaultModelSelection, threadId],
+ [
+ draftThread,
+ fallbackDraftProject?.defaultModelSelection,
+ settings.defaultModelSelection,
+ threadId,
+ ],
);
// Promotion is data-driven: the draft route keeps rendering while the
// server thread (same pre-allocated ref) starts, so live state must not
@@ -1987,6 +1996,12 @@ export default function ChatView(props: ChatViewProps) {
[activeThread?.environmentId, activeThread?.projectId],
);
const activeProject = useProject(activeProjectRef);
+ const activeProjectScripts = useMemo(
+ () => (activeProject ? resolveProjectScripts(settings, activeProject) : []),
+ [activeProject, settings],
+ );
+ const activeProjectDefaultModelSelection =
+ activeProject?.defaultModelSelection ?? settings.defaultModelSelection;
const handleNewThreadInActiveProject = useCallback(() => {
startNewThreadForProject(activeProjectRef, handleNewThread);
}, [activeProjectRef, handleNewThread]);
@@ -2035,8 +2050,8 @@ export default function ChatView(props: ChatViewProps) {
[activeProjectKey],
);
const configuredPreviewUrls = useMemo(
- () => getConfiguredPreviewUrls(activeProject?.scripts),
- [activeProject?.scripts],
+ () => getConfiguredPreviewUrls(activeProjectScripts),
+ [activeProjectScripts],
);
useEffect(() => {
@@ -2280,7 +2295,7 @@ export default function ChatView(props: ChatViewProps) {
const selectedProviderByThreadId = composerActiveProvider ?? null;
const threadProvider =
activeThread?.modelSelection.instanceId ??
- activeProject?.defaultModelSelection?.instanceId ??
+ activeProjectDefaultModelSelection?.instanceId ??
null;
const lockedProvider = deriveLockedProvider({
thread: activeThread,
@@ -2514,14 +2529,14 @@ export default function ChatView(props: ChatViewProps) {
selectedProviderByThreadId,
activeThread?.session?.providerInstanceId,
activeThread?.modelSelection.instanceId,
- activeProject?.defaultModelSelection?.instanceId,
+ activeProjectDefaultModelSelection?.instanceId,
],
lockedProvider,
lockedInstanceId:
activeThread?.session?.providerInstanceId ?? activeThread?.modelSelection.instanceId,
}),
[
- activeProject?.defaultModelSelection?.instanceId,
+ activeProjectDefaultModelSelection?.instanceId,
activeThread?.modelSelection.instanceId,
activeThread?.session?.providerInstanceId,
lockedProvider,
@@ -3652,11 +3667,14 @@ export default function ChatView(props: ChatViewProps) {
keybindingCommand: KeybindingCommand;
}): Promise<AtomCommandResult<void, unknown>> => {
const updateResult = mapAtomCommandResult(
- await updateProject({
+ await updateProjectScriptSettings({
environmentId,
input: {
- projectId: input.projectId,
- scripts: input.nextScripts,
+ patch: {
+ projectScriptOverrides: {
+ [input.projectId]: input.nextScripts,
+ },
+ },
},
}),
() => undefined,
@@ -3681,7 +3699,7 @@ export default function ChatView(props: ChatViewProps) {
}
return updateResult;
},
- [environmentId, updateProject, upsertKeybinding],
+ [environmentId, updateProjectScriptSettings, upsertKeybinding],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput): Promise<AtomCommandResult<void, unknown>> => {
@@ -3690,28 +3708,28 @@ export default function ChatView(props: ChatViewProps) {
}
const nextId = nextProjectScriptId(
input.name,
- activeProject.scripts.map((script) => script.id),
+ activeProjectScripts.map((script) => script.id),
);
const nextScript = buildProjectScript(nextId, input);
const nextScripts = input.runOnWorktreeCreate
? [
- ...activeProject.scripts.map((script) =>
+ ...activeProjectScripts.map((script) =>
script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
),
nextScript,
]
- : [...activeProject.scripts, nextScript];
+ : [...activeProjectScripts, nextScript];
return persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.workspaceRoot,
- previousScripts: activeProject.scripts,
+ previousScripts: activeProjectScripts,
nextScripts,
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(nextId),
});
},
- [activeProject, persistProjectScripts],
+ [activeProject, activeProjectScripts, persistProjectScripts],
);
const updateProjectScript = useCallback(
async (
@@ -3721,13 +3739,13 @@ export default function ChatView(props: ChatViewProps) {
if (!activeProject) {
return AsyncResult.success(undefined);
}
- const existingScript = activeProject.scripts.find((script) => script.id === scriptId);
+ const existingScript = activeProjectScripts.find((script) => script.id === scriptId);
if (!existingScript) {
return AsyncResult.failure(Cause.fail(new Error("Script not found.")));
}
const updatedScript = buildProjectScript(existingScript.id, input);
- const nextScripts = activeProject.scripts.map((script) =>
+ const nextScripts = activeProjectScripts.map((script) =>
script.id === scriptId
? updatedScript
: input.runOnWorktreeCreate
@@ -3738,27 +3756,27 @@ export default function ChatView(props: ChatViewProps) {
return persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.workspaceRoot,
- previousScripts: activeProject.scripts,
+ previousScripts: activeProjectScripts,
nextScripts,
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(scriptId),
});
},
- [activeProject, persistProjectScripts],
+ [activeProject, activeProjectScripts, persistProjectScripts],
);
const deleteProjectScript = useCallback(
async (scriptId: string): Promise<AtomCommandResult<void, unknown>> => {
if (!activeProject) {
return AsyncResult.success(undefined);
}
- const nextScripts = activeProject.scripts.filter((script) => script.id !== scriptId);
+ const nextScripts = activeProjectScripts.filter((script) => script.id !== scriptId);
- const deletedName = activeProject.scripts.find((s) => s.id === scriptId)?.name;
+ const deletedName = activeProjectScripts.find((s) => s.id === scriptId)?.name;
const result = await persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.workspaceRoot,
- previousScripts: activeProject.scripts,
+ previousScripts: activeProjectScripts,
nextScripts,
keybinding: null,
keybindingCommand: commandForProjectScript(scriptId),
@@ -3780,7 +3798,7 @@ export default function ChatView(props: ChatViewProps) {
}
return result;
},
- [activeProject, persistProjectScripts],
+ [activeProject, activeProjectScripts, persistProjectScripts],
);
const handleRuntimeModeChange = useCallback(
@@ -6061,7 +6079,7 @@ export default function ChatView(props: ChatViewProps) {
const scriptId = projectScriptIdFromCommand(command);
if (!scriptId || !activeProject) return;
- const script = activeProject.scripts.find((entry) => entry.id === scriptId);
+ const script = activeProjectScripts.find((entry) => entry.id === scriptId);
if (!script) return;
event.preventDefault();
event.stopPropagation();
@@ -6072,6 +6090,7 @@ export default function ChatView(props: ChatViewProps) {
}, [
activeProject,
activeRightPanelSurface,
+ activeProjectScripts,
addTerminalSurface,
activeThreadRef,
activeThreadPinned,
@@ -6747,7 +6766,7 @@ export default function ChatView(props: ChatViewProps) {
const title = truncate(titleSeed);
const threadCreateModelSelection = createModelSelection(
ctxSelectedModelSelection.instanceId,
- ctxSelectedModel || activeProject.defaultModelSelection?.model || DEFAULT_MODEL,
+ ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL,
ctxSelectedModelSelection.options,
);
@@ -7885,7 +7904,7 @@ export default function ChatView(props: ChatViewProps) {
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
activeProjectIcon={activeProject?.projectIcon ?? null}
openInCwd={gitCwd}
- activeProjectScripts={activeProject?.scripts}
+ activeProjectScripts={activeProjectScripts}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
@@ -8124,9 +8143,7 @@ export default function ChatView(props: ChatViewProps) {
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
- activeProjectDefaultModelSelection={
- activeProject?.defaultModelSelection
- }
+ activeProjectDefaultModelSelection={activeProjectDefaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeContextWindow={activeContextWindow}
compactThreadUnavailable={compactThreadUnavailable}
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index b0dd3febebc..e54671f8e2f 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -1791,6 +1791,8 @@ function OpenCommandPaletteDialog(props: {
run: async () => {
await navigate({
to: item.to,
+ search: (previous) =>
+ item.to === "/settings/projects" ? { ...previous, project: undefined } : previous,
hash: item.targetId ?? item.id,
replace: pathname === item.to,
hashScrollIntoView: false,
diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx
index 04bbeb6ce49..98f9caa2300 100644
--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx
+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx
@@ -149,8 +149,13 @@ export function DraftHeroHeadline({
);
if (!hasExplicitComposerModelSelection(currentDraft)) {
applyStickyState(draftId);
- if (project.defaultModelSelection) {
- setModelSelection(draftId, project.defaultModelSelection, {
+ const defaultModelSelection =
+ project.defaultModelSelection ??
+ environments.find(
+ (environment) => environment.environmentId === project.environmentId,
+ )?.serverConfig?.settings.defaultModelSelection;
+ if (defaultModelSelection) {
+ setModelSelection(draftId, defaultModelSelection, {
replaceOptions: true,
});
}
diff --git a/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx b/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx
index e97a46a2a25..3e941e69dd5 100644
--- a/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx
+++ b/apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx
@@ -6,7 +6,6 @@ import { handleDesktopAppActivationRequest } from "../../desktopAppActivation";
import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
import { findProjectByPath, inferProjectTitleFromPath } from "../../lib/projectPaths";
import { newProjectId } from "../../lib/utils";
-import { resolveDefaultProviderModelSelection } from "../../providerInstances";
import { readProjects, waitForProject } from "../../state/entities";
import { usePrimaryEnvironment } from "../../state/environments";
import { projectEnvironment } from "../../state/projects";
@@ -52,10 +51,6 @@ export function DesktopAppActivationCoordinator() {
) ?? null,
createProject: async (environmentId, workspaceRoot) => {
const projectId = newProjectId();
- const providers =
- primaryEnvironment?.environmentId === environmentId
- ? (primaryEnvironment.serverConfig?.providers ?? [])
- : [];
const result = await createProject({
environmentId,
input: {
@@ -63,7 +58,7 @@ export function DesktopAppActivationCoordinator() {
title: inferProjectTitleFromPath(workspaceRoot),
workspaceRoot,
createWorkspaceRootIfMissing: false,
- defaultModelSelection: resolveDefaultProviderModelSelection(providers, null),
+ defaultModelSelection: null,
},
});
if (result._tag === "Failure") {
diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx
index cb31ef25966..62665aa86eb 100644
--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx
+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx
@@ -51,7 +51,6 @@ import {
} from "../../onboarding/targetEnvironment.logic";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { newProjectId, randomUUID } from "../../lib/utils";
-import { resolveDefaultProviderModelSelection } from "../../providerInstances";
import { agentSessionImport, agentSessionScan } from "../../state/agentSessions";
import { readProjects, useProjects } from "../../state/entities";
import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
@@ -1029,9 +1028,6 @@ function ImportStep({
const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);
const environmentId = targetEnvironment?.environmentId ?? null;
const machineLabel = targetEnvironment?.label ?? "this machine";
- const providers = useAtomValue(
- serverEnvironment.providersValueAtom(environmentId ?? ("" as EnvironmentId)),
- );
const scan = useEnvironmentQuery(
environmentId === null ? null : agentSessionScan({ environmentId, input: {} }),
);
@@ -1123,7 +1119,6 @@ function ImportStep({
const importGeneration = importGenerationRef.current;
const importedProjects = importedProjectsRef.current;
const projectAttempts = projectAttemptsRef.current;
- const defaultModelSelection = resolveDefaultProviderModelSelection(providers ?? [], null);
// Interrupted imports are neither failures nor successes — the command was
// superseded or the environment dropped — but they still didn't land, so
// they must not read as "imported everything". Retries skip paths that
@@ -1164,7 +1159,7 @@ function ImportStep({
title: candidate.title,
workspaceRoot: candidate.path,
createWorkspaceRootIfMissing: false,
- defaultModelSelection,
+ defaultModelSelection: null,
},
});
if (
diff --git a/apps/web/src/components/settings/IntegrationsSettings.test.tsx b/apps/web/src/components/settings/IntegrationsSettings.test.tsx
index 1a8dc7d6aae..5d185fee582 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.test.tsx
+++ b/apps/web/src/components/settings/IntegrationsSettings.test.tsx
@@ -1,4 +1,10 @@
import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts";
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRouter,
+ RouterProvider,
+} from "@tanstack/react-router";
import { act, StrictMode, type ReactNode } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -44,13 +50,19 @@ afterEach(async () => {
});
async function openSettings() {
+ const router = createRouter({
+ routeTree: createRootRoute({ component: IntegrationsSettingsPanel }),
+ history: createMemoryHistory(),
+ });
+ await router.load();
await act(() => {
renderer = create(
<StrictMode>
- <IntegrationsSettingsPanel />
+ <RouterProvider router={router} />
</StrictMode>,
);
});
+ expect(renderer!.root.findByType(IntegrationsSettingsPanel)).toBeDefined();
}
describe("Integrations browser discovery", () => {
diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx
index e950bab31cb..514c241a3c5 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.tsx
+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx
@@ -20,7 +20,6 @@ import {
DEFAULT_BROWSER_RECORDING_FRAME_RATE,
DEFAULT_BROWSER_VIEWPORT,
DEFAULT_PREVIEW_APPEARANCE,
- DEFAULT_UNIFIED_SETTINGS,
DEFAULT_PREVIEW_ZOOM_FACTOR,
FILL_PREVIEW_VIEWPORT,
PREVIEW_VIEWPORT_MAX_AREA,
@@ -35,6 +34,7 @@ import {
type PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
+import { Link } from "@tanstack/react-router";
import { InfoIcon, MoreVertical, Plus as PlusIcon } from "lucide-react";
import { useCallback, useRef, useState, type ReactNode } from "react";
@@ -86,7 +86,6 @@ import {
persistClientSettingsUpdate,
useClientSettings,
useClientSettingsHydrated,
- usePrimarySettings,
useUpdatePrimarySettings,
} from "~/hooks/useSettings";
@@ -552,39 +551,20 @@ function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean })
}
function AgentBrowserAccessSetting() {
- const settings = usePrimarySettings();
- const updateSettings = useUpdatePrimarySettings();
-
return (
<SettingsRow
- serverScoped
{...searchableSetting("agent-browser-access")}
- description="Allow agents to use the preview browser. Off hides browser tools from agents, not you."
- status={
- settings.enableAgentBrowserAccess
- ? undefined
- : "Applies to sessions started from now on; a running agent keeps the tools it was given."
- }
- resetAction={
- settings.enableAgentBrowserAccess !== DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess ? (
- <SettingResetButton
- label="agent browser access"
- onClick={() =>
- updateSettings({
- enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess,
- })
- }
- />
- ) : null
- }
+ description="Choose whether agents can use the preview browser for all projects or a specific project."
control={
- <Switch
- checked={settings.enableAgentBrowserAccess}
- onCheckedChange={(checked) =>
- updateSettings({ enableAgentBrowserAccess: Boolean(checked) })
+ <Button
+ render={
+ <Link to="/settings/projects" search={{ project: undefined, machine: undefined }} />
}
- aria-label="Allow agent browser access"
- />
+ size="sm"
+ variant="outline"
+ >
+ Project settings
+ </Button>
}
/>
);
diff --git a/apps/web/src/components/settings/ProjectActionsList.tsx b/apps/web/src/components/settings/ProjectActionsList.tsx
new file mode 100644
index 00000000000..1794a5fdaa2
--- /dev/null
+++ b/apps/web/src/components/settings/ProjectActionsList.tsx
@@ -0,0 +1,69 @@
+import type { ProjectScript, ResolvedKeybindingsConfig } from "@t3tools/contracts";
+import { SettingsIcon } from "lucide-react";
+import { shortcutLabelForCommand } from "../../keybindings";
+import { commandForProjectScript } from "../../projectScripts";
+import { ScriptIcon } from "../projectScriptEditor";
+import { Button } from "../ui/button";
+import { SettingsRow } from "./settingsLayout";
+
+export function ProjectActionsList({
+ scripts,
+ keybindings,
+ disabled,
+ onEdit,
+}: {
+ scripts: readonly ProjectScript[];
+ keybindings: ResolvedKeybindingsConfig;
+ disabled: boolean;
+ onEdit: (script: ProjectScript) => void;
+}) {
+ if (scripts.length === 0)
+ return (
+ <p className="px-3 py-2 text-base text-muted-foreground sm:px-4 sm:text-sm">
+ No actions configured.
+ </p>
+ );
+ return scripts.map((script) => {
+ const shortcutLabel = shortcutLabelForCommand(keybindings, commandForProjectScript(script.id));
+ return (
+ <SettingsRow
+ key={script.id}
+ className="group py-2"
+ title={
+ <span className="flex min-w-0 items-center gap-2">
+ <ScriptIcon icon={script.icon} className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 truncate">{script.name}</span>
+ {script.runOnWorktreeCreate ? (
+ <span className="shrink-0 rounded-sm border border-border/60 px-1.5 py-px text-[11px] font-normal text-muted-foreground">
+ setup
+ </span>
+ ) : null}
+ {script.previewUrl ? (
+ <span className="shrink-0 rounded-sm border border-border/60 px-1.5 py-px text-[11px] font-normal text-muted-foreground max-sm:hidden">
+ preview · desktop only
+ </span>
+ ) : null}
+ </span>
+ }
+ description={<code className="block max-w-full truncate font-mono">{script.command}</code>}
+ control={
+ <>
+ {shortcutLabel ? (
+ <span className="text-xs text-muted-foreground">{shortcutLabel}</span>
+ ) : null}
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="shrink-0 text-muted-foreground opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"
+ aria-label={`Edit ${script.name}`}
+ disabled={disabled}
+ onClick={() => onEdit(script)}
+ >
+ <SettingsIcon className="size-3.5" />
+ </Button>
+ </>
+ }
+ />
+ );
+ });
+}
diff --git a/apps/web/src/components/settings/ProjectDefaultActionsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultActionsSettings.tsx
new file mode 100644
index 00000000000..4385a5901b5
--- /dev/null
+++ b/apps/web/src/components/settings/ProjectDefaultActionsSettings.tsx
@@ -0,0 +1,114 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
+import { PlusIcon } from "lucide-react";
+import { useState } from "react";
+import { useEnvironments } from "../../state/environments";
+import {
+ EMPTY_PROJECT_SCRIPT_INPUT,
+ editorRequestForScript,
+ ProjectScriptEditorDialog,
+ type ProjectScriptEditorRequest,
+} from "../projectScriptEditor";
+import { Button } from "../ui/button";
+import { ProjectActionsList } from "./ProjectActionsList";
+import { useProjectScriptSettings } from "./ProjectSettingsPanel";
+import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
+
+export function ProjectDefaultActionsSettings({
+ environmentId,
+}: {
+ environmentId: EnvironmentId | null;
+}) {
+ const { environments } = useEnvironments();
+ const targets = environments.filter(
+ (environment) =>
+ (environmentId === null || environment.environmentId === environmentId) &&
+ environment.connection.phase === "connected" &&
+ environment.serverConfig !== null,
+ );
+ const representative = targets[0]?.serverConfig;
+ const scripts = representative?.settings.defaultProjectScripts ?? [];
+ const keybindings = representative?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
+ const mixed = targets.some(
+ (target) =>
+ JSON.stringify(target.serverConfig?.settings.defaultProjectScripts) !==
+ JSON.stringify(scripts),
+ );
+ const [request, setRequest] = useState<ProjectScriptEditorRequest | null>(null);
+ const { saving, persist, submit } = useProjectScriptSettings(
+ targets.flatMap(({ environmentId, serverConfig }) =>
+ serverConfig
+ ? [
+ {
+ environmentId,
+ settings: serverConfig.settings,
+ keybindings: serverConfig.keybindings,
+ },
+ ]
+ : [],
+ ),
+ );
+
+ return (
+ <SettingsSection title="Actions">
+ <SettingsRow
+ title="Import scripts"
+ aria-disabled
+ description="Select a project to import actions from its checkout's t3.json."
+ control={
+ <Button size="xs" variant="ghost" disabled>
+ Import scripts
+ </Button>
+ }
+ />
+ <SettingsRow
+ title="Default actions"
+ description="Available in every inheriting checkout. Commands run in that checkout or its worktree."
+ resetAction={
+ targets.some(
+ (target) => (target.serverConfig?.settings.defaultProjectScripts.length ?? 0) > 0,
+ ) ? (
+ <SettingResetButton
+ label="default actions"
+ disabled={saving}
+ onClick={() => void persist(() => [])}
+ />
+ ) : null
+ }
+ control={
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={saving || targets.length === 0}
+ onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}
+ >
+ <PlusIcon className="size-3.5" />
+ Add action
+ </Button>
+ }
+ />
+ {mixed ? (
+ <SettingsRow
+ title="Different actions across machines"
+ description="Select a machine to edit its actions. Adding an action applies to all selected connected machines."
+ />
+ ) : (
+ <ProjectActionsList
+ scripts={scripts}
+ keybindings={keybindings}
+ disabled={saving}
+ onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}
+ />
+ )}
+ <ProjectScriptEditorDialog
+ request={request}
+ scripts={scripts}
+ onSubmit={submit}
+ onDelete={(id) =>
+ void persist((current) => current.filter((script) => script.id !== id), id, null)
+ }
+ onClose={() => setRequest(null)}
+ />
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
new file mode 100644
index 00000000000..938000e0100
--- /dev/null
+++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
@@ -0,0 +1,474 @@
+import {
+ DEFAULT_CLIENT_SETTINGS,
+ DEFAULT_SERVER_SETTINGS,
+ type EnvironmentId,
+ type ModelSelection,
+ type ProviderInstanceId,
+ type ServerSettingsPatch,
+} from "@t3tools/contracts";
+import { createModelSelection } from "@t3tools/shared/model";
+import { useNavigate } from "@tanstack/react-router";
+import { useRef, useState } from "react";
+import { Trash2Icon } from "lucide-react";
+
+import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
+import { getCustomModelOptionsByInstance } from "../../modelSelection";
+import {
+ applyProviderInstanceSettings,
+ deriveProviderInstanceEntries,
+ resolveDefaultProviderModelSelection,
+ sortProviderInstanceEntries,
+} from "../../providerInstances";
+import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
+import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { resolveEnvModeLabel } from "../BranchToolbar.logic";
+import { ProviderModelPicker } from "../chat/ProviderModelPicker";
+import { TraitsPicker } from "../chat/TraitsPicker";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { toastManager } from "../ui/toast";
+import { Switch } from "../ui/switch";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { PROJECT_GROUPING_MODE_LABELS } from "./ProjectSettingsPanel";
+import { ProjectDefaultActionsSettings } from "./ProjectDefaultActionsSettings";
+import { searchableSetting } from "./settingsSearch";
+import {
+ SETTINGS_PICKER_TRIGGER_CLASSNAME,
+ SettingResetButton,
+ SettingsPageContainer,
+ SettingsRow,
+ SettingsSection,
+} from "./settingsLayout";
+
+/** Defaults are written only to the machines selected on the projects settings page. */
+export function ProjectDefaultsSettings({
+ environmentId,
+}: {
+ environmentId: EnvironmentId | null;
+}) {
+ const { environments } = useEnvironments();
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const clientSettings = useClientSettings();
+ const updateClientSettings = useUpdateClientSettings();
+ const navigate = useNavigate();
+ const updateSettings = useAtomCommand(
+ serverEnvironment.updateSettings,
+ "project defaults update",
+ );
+ const savingRef = useRef(new Set<string>());
+ const [saving, setSaving] = useState<ReadonlySet<string>>(new Set());
+ const scoped = environments.filter(
+ (environment) => environmentId === null || environment.environmentId === environmentId,
+ );
+ const targets = scoped.filter(
+ (environment) =>
+ environment.connection.phase === "connected" && environment.serverConfig !== null,
+ );
+ const representative =
+ targets.find((environment) => environment.environmentId === primaryEnvironmentId) ?? targets[0];
+ const serverSettings = representative?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS;
+ const providers = representative?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
+ const settings = { ...serverSettings, ...clientSettings };
+ const storedSelection = serverSettings.defaultModelSelection;
+ const selection = resolveDefaultProviderModelSelection(providers, storedSelection);
+ const entries = sortProviderInstanceEntries(
+ applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
+ );
+ const modelOptions = getCustomModelOptionsByInstance(
+ settings,
+ providers,
+ selection?.instanceId,
+ selection?.model,
+ );
+ const activeEntry = entries.find((entry) => entry.instanceId === selection?.instanceId);
+ const mixedModel = targets.some(
+ (target) =>
+ JSON.stringify(target.serverConfig?.settings.defaultModelSelection) !==
+ JSON.stringify(storedSelection),
+ );
+ const mixedWorkspace = targets.some(
+ (target) =>
+ target.serverConfig?.settings.defaultThreadEnvMode !== serverSettings.defaultThreadEnvMode,
+ );
+ const mixedBrowser = targets.some(
+ (target) =>
+ target.serverConfig?.settings.enableAgentBrowserAccess !==
+ serverSettings.enableAgentBrowserAccess,
+ );
+ const disabled = (key: keyof ServerSettingsPatch) => targets.length === 0 || saving.has(key);
+ const mixedAutoPull = targets.some(
+ (target) => target.serverConfig?.settings.defaultAutoPull !== serverSettings.defaultAutoPull,
+ );
+
+ function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
+ const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
+ for (const target of targets) {
+ const config = target.serverConfig;
+ if (!config) continue;
+ const entry = applyProviderInstanceSettings(
+ deriveProviderInstanceEntries(config.providers),
+ config.settings,
+ ).find((candidate) => candidate.instanceId === instanceId);
+ const options = getCustomModelOptionsByInstance(
+ { ...config.settings, ...clientSettings },
+ config.providers,
+ ).get(instanceId);
+ if (
+ !entry?.enabled ||
+ !entry.isAvailable ||
+ entry.driverKind !== sourceEntry?.driverKind ||
+ !options?.some((option) => option.slug === model && !option.isUnavailable)
+ ) {
+ return `This model is unavailable on ${target.label}. Select that machine to choose its default separately.`;
+ }
+ }
+ return null;
+ }
+
+ async function save(patch: ServerSettingsPatch) {
+ const keys = Object.keys(patch);
+ if (targets.length === 0 || keys.some((key) => savingRef.current.has(key))) return;
+ const nextModel = patch.defaultModelSelection;
+ const reason = nextModel ? modelDisabledReason(nextModel.instanceId, nextModel.model) : null;
+ if (reason) {
+ toastManager.add({ type: "error", title: "Default model not saved", description: reason });
+ return;
+ }
+ for (const key of keys) savingRef.current.add(key);
+ setSaving(new Set(savingRef.current));
+ try {
+ const results = await Promise.all(
+ targets.map((target) =>
+ updateSettings({ environmentId: target.environmentId, input: { patch } }),
+ ),
+ );
+ const failedTargets = targets.filter((_, index) => results[index]?._tag === "Failure");
+ if (failedTargets.length > 0) {
+ toastManager.add({
+ type: "error",
+ title: "Project defaults not saved on every machine",
+ description: `Could not update ${failedTargets.map((target) => target.label).join(", ")}. Other machines may have saved the change.`,
+ });
+ }
+ } finally {
+ for (const key of keys) savingRef.current.delete(key);
+ setSaving(new Set(savingRef.current));
+ }
+ }
+
+ const setModel = (value: ModelSelection | null) => void save({ defaultModelSelection: value });
+ return (
+ <SettingsPageContainer>
+ <SettingsSection
+ id={searchableSetting("project-defaults").id}
+ title="Project defaults"
+ hideTitle
+ >
+ <SettingsRow
+ title="Name"
+ aria-disabled
+ description="Select a project to change its name."
+ control={
+ <Input
+ size="sm"
+ className="w-full sm:w-64"
+ aria-label="Project name"
+ placeholder="Select a project"
+ disabled
+ />
+ }
+ />
+ <SettingsRow
+ title="Project icon"
+ aria-disabled
+ description="Select a project to change its icon."
+ control={
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" disabled>
+ Choose icon
+ </Button>
+ <Button size="sm" variant="outline" disabled>
+ Choose file
+ </Button>
+ </div>
+ }
+ />
+ {scoped.length > targets.length || targets.length === 0 ? (
+ <p role="status" className="px-4 py-3 text-sm text-muted-foreground">
+ {targets.length === 0
+ ? "Connect a machine to change its project defaults."
+ : "Changes apply to connected machines only. Offline machines keep their current defaults."}
+ </p>
+ ) : null}
+ <SettingsRow
+ title="Model"
+ description="Default model for new threads. Projects can override it."
+ status={
+ targets.length === 0
+ ? undefined
+ : mixedModel
+ ? "Differs by machine"
+ : storedSelection === null
+ ? "Automatic"
+ : undefined
+ }
+ resetAction={
+ storedSelection !== null || mixedModel ? (
+ <SettingResetButton
+ label="default model"
+ disabled={disabled("defaultModelSelection")}
+ onClick={() => setModel(null)}
+ />
+ ) : null
+ }
+ control={
+ selection && activeEntry ? (
+ <fieldset
+ disabled={disabled("defaultModelSelection")}
+ className="flex min-w-0 flex-wrap items-center justify-end gap-1.5 disabled:opacity-50"
+ >
+ <ProviderModelPicker
+ activeInstanceId={selection.instanceId}
+ model={selection.model}
+ lockedProvider={null}
+ instanceEntries={entries}
+ modelOptionsByInstance={modelOptions}
+ disabled={disabled("defaultModelSelection")}
+ triggerVariant="outline"
+ triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
+ getModelDisabledReason={modelDisabledReason}
+ onOpenProviderSetup={(instanceId) => {
+ if (representative)
+ void navigate({
+ to: "/settings/providers",
+ search: { environmentId: representative.environmentId, instanceId },
+ });
+ }}
+ onInstanceModelChange={(instanceId, model) =>
+ setModel(createModelSelection(instanceId, model))
+ }
+ />
+ {!mixedModel ? (
+ <TraitsPicker
+ provider={activeEntry.driverKind}
+ models={activeEntry.models}
+ model={selection.model}
+ prompt=""
+ onPromptChange={() => {}}
+ modelOptions={selection.options ?? []}
+ allowPromptInjectedEffort={false}
+ planModeEnabled={settings.planModeEnabled}
+ triggerVariant="outline"
+ triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
+ onModelOptionsChange={(options) =>
+ setModel(createModelSelection(selection.instanceId, selection.model, options))
+ }
+ />
+ ) : null}
+ </fieldset>
+ ) : (
+ <span className="text-sm text-muted-foreground">No providers available</span>
+ )
+ }
+ />
+ <SettingsRow
+ id={searchableSetting("new-threads").id}
+ title="Workspace"
+ description="Where new threads start, unless overridden by the project or t3.json."
+ resetAction={
+ mixedWorkspace ||
+ serverSettings.defaultThreadEnvMode !== DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode ? (
+ <SettingResetButton
+ label="default workspace"
+ disabled={disabled("defaultThreadEnvMode")}
+ onClick={() =>
+ void save({ defaultThreadEnvMode: DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode })
+ }
+ />
+ ) : null
+ }
+ control={
+ <Select
+ disabled={disabled("defaultThreadEnvMode")}
+ value={mixedWorkspace ? "mixed" : serverSettings.defaultThreadEnvMode}
+ onValueChange={(value) => {
+ if (value === "local" || value === "worktree")
+ void save({ defaultThreadEnvMode: value });
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Default workspace">
+ <SelectValue>
+ {targets.length === 0
+ ? "Unavailable"
+ : mixedWorkspace
+ ? "Differs by machine"
+ : resolveEnvModeLabel(serverSettings.defaultThreadEnvMode)}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
+ <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
+ </SelectPopup>
+ </Select>
+ }
+ />
+ <SettingsRow
+ title="Automatically pull"
+ description="Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
+ status={mixedAutoPull ? "Differs by machine" : undefined}
+ resetAction={
+ serverSettings.defaultAutoPull || mixedAutoPull ? (
+ <SettingResetButton
+ label="default automatic pull"
+ tooltip="Reset automatic pull to off"
+ disabled={disabled("defaultAutoPull")}
+ onClick={() => void save({ defaultAutoPull: false })}
+ />
+ ) : null
+ }
+ control={
+ <Switch
+ aria-label="Default automatic pull"
+ checked={serverSettings.defaultAutoPull}
+ disabled={disabled("defaultAutoPull")}
+ onCheckedChange={(enabled) => void save({ defaultAutoPull: enabled })}
+ />
+ }
+ />
+ <SettingsRow
+ id={searchableSetting("agent-browser-access").id}
+ title="Agent browser access"
+ description="Allow agents to use the shared browser. Projects can override it."
+ resetAction={
+ mixedBrowser ||
+ serverSettings.enableAgentBrowserAccess !==
+ DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
+ <SettingResetButton
+ label="default browser access"
+ disabled={disabled("enableAgentBrowserAccess")}
+ onClick={() =>
+ void save({
+ enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
+ })
+ }
+ />
+ ) : null
+ }
+ control={
+ <Select
+ disabled={disabled("enableAgentBrowserAccess")}
+ value={
+ mixedBrowser
+ ? "mixed"
+ : serverSettings.enableAgentBrowserAccess
+ ? "enabled"
+ : "disabled"
+ }
+ onValueChange={(value) => {
+ if (value === "enabled" || value === "disabled")
+ void save({ enableAgentBrowserAccess: value === "enabled" });
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Default agent browser access">
+ <SelectValue>
+ {targets.length === 0
+ ? "Unavailable"
+ : mixedBrowser
+ ? "Differs by machine"
+ : serverSettings.enableAgentBrowserAccess
+ ? "Enabled"
+ : "Disabled"}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="enabled">Enabled</SelectItem>
+ <SelectItem value="disabled">Disabled</SelectItem>
+ </SelectPopup>
+ </Select>
+ }
+ />
+ </SettingsSection>
+ <SettingsSection title="Checkout">
+ <SettingsRow
+ title="Checkout"
+ aria-disabled
+ description="Select a project to choose one of its checkouts."
+ control={
+ <Select disabled>
+ <SelectTrigger size="sm" aria-label="Checkout">
+ <SelectValue placeholder="Select a project" />
+ </SelectTrigger>
+ </Select>
+ }
+ />
+ <SettingsRow
+ title="Project grouping"
+ description="Default grouping across all machines in this client. Individual checkout overrides are preserved."
+ resetAction={
+ clientSettings.sidebarProjectGroupingMode !==
+ DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode ? (
+ <SettingResetButton
+ label="default project grouping"
+ onClick={() =>
+ void updateClientSettings({
+ sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode,
+ })
+ }
+ />
+ ) : null
+ }
+ control={
+ <Select
+ value={clientSettings.sidebarProjectGroupingMode}
+ onValueChange={(value) => {
+ if (value === "repository" || value === "repository_path" || value === "separate")
+ void updateClientSettings({ sidebarProjectGroupingMode: value });
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Default project grouping">
+ <SelectValue>
+ {PROJECT_GROUPING_MODE_LABELS[clientSettings.sidebarProjectGroupingMode]}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="repository">
+ {PROJECT_GROUPING_MODE_LABELS.repository}
+ </SelectItem>
+ <SelectItem value="repository_path">
+ {PROJECT_GROUPING_MODE_LABELS.repository_path}
+ </SelectItem>
+ <SelectItem value="separate">{PROJECT_GROUPING_MODE_LABELS.separate}</SelectItem>
+ </SelectPopup>
+ </Select>
+ }
+ />
+ <SettingsRow
+ title="Remove checkout"
+ aria-disabled
+ description="Select a project to remove one of its checkouts."
+ control={
+ <Button size="sm" variant="destructive-outline" disabled>
+ <Trash2Icon className="size-3.5" />
+ Remove checkout
+ </Button>
+ }
+ />
+ </SettingsSection>
+ <ProjectDefaultActionsSettings environmentId={environmentId} />
+ <SettingsSection title="Danger">
+ <SettingsRow
+ title="Remove project"
+ aria-disabled
+ description="Select a project to remove its entries and threads. Files on disk are not touched."
+ control={
+ <Button size="sm" variant="destructive-outline" disabled>
+ <Trash2Icon />
+ Remove project
+ </Button>
+ }
+ />
+ </SettingsSection>
+ </SettingsPageContainer>
+ );
+}
diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx
index 0181041ec6b..f4ffe699466 100644
--- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx
+++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx
@@ -12,52 +12,53 @@ import {
deriveProjectGroupingOverrideKey,
selectProjectGroupingSettings,
} from "../../logicalProject";
-import type {
- ContextMenuItem,
- ModelSelection,
- ProjectIconOverride,
- ProviderDriverKind,
- SidebarProjectGroupingMode,
- T3ProjectFileScript,
- ThreadEnvMode,
+import {
+ type EnvironmentId,
+ type ModelSelection,
+ type ProjectIconOverride,
+ type ProjectId,
+ type ProjectScript,
+ type ResolvedKeybindingsConfig,
+ type ServerSettings,
+ type ProviderDriverKind,
+ type SidebarProjectGroupingMode,
+ type T3ProjectFileScript,
+ type ThreadEnvMode,
} from "@t3tools/contracts";
import { resolveEnvModeLabel } from "../BranchToolbar.logic";
import { createModelSelection } from "@t3tools/shared/model";
+import { resolveProjectAutoPull } from "@t3tools/shared/serverSettings";
+import {
+ projectScriptsInheritDefaults,
+ resolveProjectScripts,
+} from "@t3tools/shared/projectScripts";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
-import { useCanGoBack, useNavigate } from "@tanstack/react-router";
+import { useNavigate } from "@tanstack/react-router";
+import * as Equal from "effect/Equal";
import * as Cause from "effect/Cause";
-import { ChevronDownIcon, CopyIcon, PlusIcon, SettingsIcon, Trash2Icon } from "lucide-react";
-import {
- lazy,
- Suspense,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
- type MouseEvent as ReactMouseEvent,
-} from "react";
+import { ChevronDownIcon, PlusIcon, Trash2Icon } from "lucide-react";
+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useComposerDraftStore } from "../../composerDraftStore";
-import { isElectron } from "../../env";
import {
useClientSettings,
useEnvironmentSettings,
useUpdateClientSettings,
- usePrimarySettings,
} from "../../hooks/useSettings";
-import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
-import { shortcutLabelForCommand } from "../../keybindings";
-import { keybindingValueForCommand } from "../../lib/projectScriptKeybindings";
-import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";
-import { readLocalApi } from "../../localApi";
+import { ProjectActionsList } from "./ProjectActionsList";
+import { isElectron } from "../../env";
+import {
+ decodeProjectScriptKeybindingRule,
+ keybindingValueForCommand,
+} from "../../lib/projectScriptKeybindings";
import {
buildProjectScript,
commandForProjectScript,
nextProjectScriptId,
} from "../../projectScripts";
-import { decodeProjectScriptKeybindingRule } from "../../lib/projectScriptKeybindings";
+import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";
+import { readLocalApi } from "../../localApi";
import {
applyProviderInstanceSettings,
deriveProviderInstanceEntries,
@@ -98,16 +99,8 @@ import {
MenuTrigger,
} from "../ui/menu";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
-import { SidebarInset } from "../ui/sidebar";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
-import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
-import {
- WorkspaceBreadcrumb,
- WorkspaceBreadcrumbItem,
- WorkspaceBreadcrumbSeparator,
-} from "../WorkspaceBreadcrumb";
-import { WorkspacePageHeader } from "../WorkspacePageHeader";
import {
SETTINGS_PICKER_TRIGGER_CLASSNAME,
SettingResetButton,
@@ -127,14 +120,14 @@ const ProjectIconPickerDialog = lazy(() =>
})),
);
-const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = {
+export const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = {
repository: "Group by repository",
repository_path: "Group by repository path",
separate: "Keep separate",
};
/** Logical project groups for the settings page, sorted by display name. */
-function useSettingsProjectGroups(): SidebarProjectSnapshot[] {
+export function useSettingsProjectGroups(): SidebarProjectSnapshot[] {
const projects = useProjects();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -162,132 +155,59 @@ function memberKey(member: { environmentId: string; id: string }): string {
return `${member.environmentId}:${member.id}`;
}
-export function ProjectSettingsPage({ projectKey }: { projectKey: string }) {
- const navigate = useNavigate();
- const canGoBack = useCanGoBack();
- const navigateBackWithinApp = useCallback(() => {
- if (canGoBack) {
- window.history.back();
- return;
- }
- void navigate({ to: "/" });
- }, [canGoBack, navigate]);
-
- useEffect(() => {
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.defaultPrevented) return;
- if (event.key !== "Escape") return;
- event.preventDefault();
- const activeElement = document.activeElement;
- if (activeElement instanceof HTMLElement) {
- activeElement.blur();
- }
- navigateBackWithinApp();
- };
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, [navigateBackWithinApp]);
-
- return (
- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
- <WorkspacePageHeader electron={isElectron}>
- <ProjectSettingsBreadcrumb projectKey={projectKey} />
- </WorkspacePageHeader>
- <ProjectSettingsPanel projectKey={projectKey} />
- </div>
- </SidebarInset>
- );
-}
-
-function ProjectSettingsBreadcrumb({ projectKey }: { projectKey: string }) {
- const groups = useSettingsProjectGroups();
- const navigate = useNavigate();
- const selected = groups.find((group) => group.projectKey === projectKey) ?? null;
- const openProjectMenu = (event: ReactMouseEvent<HTMLButtonElement>) => {
- const api = readLocalApi();
- if (!api) return;
-
- const rect = event.currentTarget.getBoundingClientRect();
- const items: ContextMenuItem<string>[] = groups.map((group) => ({
- id: group.projectKey,
- label: group.displayName,
- }));
- void settlePromise(() =>
- api.contextMenu.show(items, { x: rect.left, y: rect.bottom + 4 }),
- ).then((clicked) => {
- if (clicked._tag === "Failure" || clicked.value === null) return;
- void navigate({
- to: "/projects/$projectKey",
- params: { projectKey: clicked.value },
- replace: true,
- hashScrollIntoView: false,
- });
- });
- };
-
- return (
- <WorkspaceBreadcrumb ariaLabel="Project settings breadcrumb">
- <WorkspaceBreadcrumbItem>Projects</WorkspaceBreadcrumbItem>
- <WorkspaceBreadcrumbSeparator />
- <WorkspaceBreadcrumbItem current>
- {selected ? (
- <button
- type="button"
- aria-haspopup="menu"
- aria-label="Switch project"
- onClick={openProjectMenu}
- className="group/project-title inline-flex min-w-0 max-w-64 cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
- >
- <span className="min-w-0 truncate">{selected.displayName}</span>
- <ChevronDownIcon
- aria-hidden
- className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/project-title:opacity-100 group-focus-visible/project-title:opacity-100"
- />
- </button>
- ) : (
- <span className="truncate text-muted-foreground">Unavailable project</span>
- )}
- </WorkspaceBreadcrumbItem>
- </WorkspaceBreadcrumb>
- );
-}
-
-function ProjectSettingsPanel({ projectKey }: { projectKey: string }) {
+export function ProjectSettingsPanel({
+ projectKey,
+ environmentId = null,
+}: {
+ projectKey: string;
+ environmentId?: EnvironmentId | null;
+}) {
const groups = useSettingsProjectGroups();
const navigate = useNavigate();
const selected = groups.find((group) => group.projectKey === projectKey) ?? null;
+ const members = useMemo(
+ () =>
+ selected?.memberProjects.filter(
+ (member) => environmentId === null || member.environmentId === environmentId,
+ ) ?? [],
+ [selected, environmentId],
+ );
// Remember the members of the last rendered group so a grouping-rule change
// (which changes the group key) can follow the project to its new group.
- const lastSelectionRef = useRef<{ key: string; memberKeys: string[] } | null>(null);
+ const lastSelectionRef = useRef<{
+ key: string;
+ environmentId: EnvironmentId | null;
+ memberKeys: string[];
+ } | null>(null);
useEffect(() => {
- if (!selected) return;
+ if (!selected || members.length === 0) return;
lastSelectionRef.current = {
key: selected.projectKey,
- memberKeys: selected.memberProjects.map((member) => member.physicalProjectKey),
+ environmentId,
+ memberKeys: members.map((member) => member.physicalProjectKey),
};
- }, [selected]);
+ }, [selected, members, environmentId]);
// A grouping-rule change replaces the group key mid-visit; follow the
// project to its new key instead of parking on the not-found state.
useEffect(() => {
- if (selected !== null) return;
+ if (members.length > 0) return;
const last = lastSelectionRef.current;
- if (last?.key !== projectKey) return;
+ if (last?.key !== projectKey || last.environmentId !== environmentId) return;
const successor = groups.find((group) =>
group.memberProjects.some((member) => last.memberKeys.includes(member.physicalProjectKey)),
);
if (successor) {
void navigate({
- to: "/projects/$projectKey",
- params: { projectKey: successor.projectKey },
+ to: "/settings/projects",
+ search: { project: successor.projectKey, machine: environmentId ?? undefined },
replace: true,
hashScrollIntoView: false,
});
}
- }, [groups, navigate, projectKey, selected]);
+ }, [groups, navigate, projectKey, members.length, environmentId]);
if (!selected) {
return (
@@ -298,17 +218,185 @@ function ProjectSettingsPanel({ projectKey }: { projectKey: string }) {
</div>
);
}
- return <ProjectDetail key={selected.projectKey} group={selected} />;
+ if (members.length === 0)
+ return (
+ <p className="p-8 text-sm text-muted-foreground">
+ This project has no checkout on this machine.
+ </p>
+ );
+ const scopedGroup = {
+ ...selected,
+ memberProjects: members,
+ environmentId: members[0]!.environmentId,
+ id: members[0]!.id,
+ };
+ return (
+ <ProjectDetail
+ key={`${selected.projectKey}:${environmentId ?? "all"}`}
+ group={scopedGroup}
+ hasOtherMembers={members.length < selected.memberProjects.length}
+ />
+ );
+}
+
+function reportScriptFailure(result: AtomCommandResult<unknown, unknown>) {
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add({
+ type: "error",
+ title: "Failed to save project actions",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ });
+ }
+ return mapAtomCommandResult(result, () => undefined);
+}
+
+export function useProjectScriptSettings(
+ targets: readonly {
+ environmentId: EnvironmentId;
+ settings: ServerSettings;
+ keybindings: ResolvedKeybindingsConfig;
+ project?: { id: ProjectId; scripts: readonly ProjectScript[] };
+ }[],
+) {
+ const projects = useProjects();
+ const [saving, setSaving] = useState(false);
+ const savingRef = useRef(false);
+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update");
+ const upsertKeybinding = useAtomCommand(
+ serverEnvironment.upsertKeybinding,
+ "action shortcut update",
+ );
+ const removeKeybinding = useAtomCommand(
+ serverEnvironment.removeKeybinding,
+ "action shortcut removal",
+ );
+
+ async function persist(
+ transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
+ scriptId?: string,
+ keybinding?: string | null,
+ ): Promise<AtomCommandResult<void, unknown>> {
+ if (savingRef.current || targets.length === 0) {
+ const message = "No available machine, or another action change is saving.";
+ toastManager.add({ type: "error", title: "Actions not saved", description: message });
+ return AsyncResult.failure(Cause.fail(new Error(message)));
+ }
+ savingRef.current = true;
+ setSaving(true);
+ try {
+ for (const { environmentId, settings, keybindings, project } of targets) {
+ const current = project
+ ? resolveProjectScripts(settings, project)
+ : settings.defaultProjectScripts;
+ const nextScripts = transform(current);
+ const effectiveScripts = nextScripts ?? settings.defaultProjectScripts;
+ const result = await updateSettings({
+ environmentId,
+ input: {
+ patch: project
+ ? { projectScriptOverrides: { [project.id]: nextScripts } }
+ : { defaultProjectScripts: nextScripts ?? [] },
+ },
+ });
+ if (result._tag === "Failure") return reportScriptFailure(result);
+ if (!isElectron) continue;
+ const changedIds = scriptId
+ ? [scriptId]
+ : current
+ .filter((script) => !effectiveScripts.some((next) => next.id === script.id))
+ .map((script) => script.id);
+ for (const id of changedIds) {
+ const command = commandForProjectScript(id);
+ const previousValue = keybindingValueForCommand(keybindings, command);
+ const previous = previousValue
+ ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
+ : null;
+ const next = decodeProjectScriptKeybindingRule({ keybinding, command });
+ const retainedElsewhere =
+ !nextScripts?.some((script) => script.id === id) &&
+ ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
+ Object.entries(settings.projectScriptOverrides).some(
+ ([projectId, scripts]) =>
+ projectId !== project?.id && scripts?.some((script) => script.id === id),
+ ) ||
+ projects.some(
+ (other) =>
+ other.environmentId === environmentId &&
+ other.id !== project?.id &&
+ (project ? resolveProjectScripts(settings, other) : other.scripts).some(
+ (script) => script.id === id,
+ ),
+ ));
+ const bindingResult = next
+ ? await upsertKeybinding({
+ environmentId,
+ input:
+ previous && previous.key !== next.key ? { ...next, replace: previous } : next,
+ })
+ : previous && !retainedElsewhere
+ ? await removeKeybinding({ environmentId, input: previous })
+ : null;
+ if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
+ }
+ }
+ return AsyncResult.success(undefined);
+ } finally {
+ savingRef.current = false;
+ setSaving(false);
+ }
+ }
+
+ function submit(scriptId: string | null, input: NewProjectScriptInput) {
+ const existingIds = [
+ ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
+ ...targets.flatMap(({ settings, project }) =>
+ [
+ ...settings.defaultProjectScripts,
+ ...Object.values(settings.projectScriptOverrides).flatMap((scripts) => scripts ?? []),
+ ...(project?.scripts ?? []),
+ ].map((script) => script.id),
+ ),
+ ];
+ const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
+ const next = buildProjectScript(id, input);
+ return persist(
+ (current) => {
+ const updated = current.map((script) =>
+ script.id === id
+ ? next
+ : input.runOnWorktreeCreate
+ ? { ...script, runOnWorktreeCreate: false }
+ : script,
+ );
+ return scriptId === null ? [...updated, next] : updated;
+ },
+ id,
+ input.keybinding,
+ );
+ }
+
+ return { saving, persist, submit };
}
-function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
+function ProjectDetail({
+ group,
+ hasOtherMembers,
+}: {
+ group: SidebarProjectSnapshot;
+ hasOtherMembers: boolean;
+}) {
const navigate = useNavigate();
const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const { environments } = useEnvironments();
+ const environmentById = useMemo(
+ () => new Map(environments.map((environment) => [environment.environmentId, environment])),
+ [environments],
+ );
const representative =
group.memberProjects.find(
- (member) => member.environmentId === group.environmentId && member.id === group.id,
+ (member) => environmentById.get(member.environmentId)?.serverConfig != null,
) ?? group.memberProjects[0]!;
- const settings = usePrimarySettings();
// Provider instances and model options belong to the environment that runs
// the project's threads. The hosted app has no primary environment, so
// reading them from there would show "No providers available" everywhere.
@@ -320,28 +408,78 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const threads = useThreadShells();
const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });
- const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
- const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
- reportFailure: false,
- });
- const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, {
- reportFailure: false,
+ const updateServerSettings = useAtomCommand(serverEnvironment.updateSettings, "project setting");
+ const [savingBrowserAccess, setSavingBrowserAccess] = useState(false);
+ const savingBrowserAccessRef = useRef(false);
+ const browserOverrides = group.memberProjects.map(
+ (member) =>
+ environmentById.get(member.environmentId)?.serverConfig?.settings
+ .projectAgentBrowserAccessOverrides[member.id],
+ );
+ const browserOverride = projectSettings.projectAgentBrowserAccessOverrides[representative.id];
+ const browserMixed = group.memberProjects.some((member, index) => {
+ const settings = environmentById.get(member.environmentId)?.serverConfig?.settings;
+ if (!settings || !environmentById.get(representative.environmentId)?.serverConfig) return false;
+ return (
+ browserOverrides[index] !== browserOverride ||
+ (browserOverrides[index] ?? settings.enableAgentBrowserAccess) !==
+ (browserOverride ?? projectSettings.enableAgentBrowserAccess)
+ );
});
+ const setBooleanOverride = async (
+ key: "projectAgentBrowserAccessOverrides" | "projectAutoPullOverrides",
+ enabled: boolean | undefined,
+ ) => {
+ if (savingBrowserAccessRef.current) return;
+ savingBrowserAccessRef.current = true;
+ setSavingBrowserAccess(true);
+ try {
+ const environmentIds = new Set(group.memberProjects.map((member) => member.environmentId));
+ for (const environmentId of environmentIds) {
+ const environment = environmentById.get(environmentId);
+ if (!environment?.serverConfig || environment.connection.phase !== "connected") {
+ toastManager.add({
+ type: "warning",
+ title: "Setting not saved",
+ description: `Connect ${environment?.label ?? "this machine"} and try again.`,
+ });
+ return;
+ }
+ }
+ if (key === "projectAutoPullOverrides" && enabled === undefined) {
+ const result = await updateAllMembers(
+ { autoPull: false },
+ "Failed to reset automatic pull",
+ );
+ if (result._tag === "Failure") return;
+ }
+ for (const environmentId of environmentIds) {
+ const overrides = Object.fromEntries(
+ group.memberProjects
+ .filter((member) => member.environmentId === environmentId)
+ .map((member) => [member.id, enabled ?? null]),
+ );
+ const result = await updateServerSettings({
+ environmentId,
+ input: { patch: { [key]: overrides } },
+ });
+ if (result._tag === "Failure") {
+ reportFailure(
+ `Failed to save project setting on ${environmentById.get(environmentId)?.label ?? "this machine"}`,
+ mapAtomCommandResult(result, () => undefined),
+ );
+ return;
+ }
+ }
+ } finally {
+ savingBrowserAccessRef.current = false;
+ setSavingBrowserAccess(false);
+ }
+ };
+ const setBrowserAccess = (enabled: boolean | undefined) =>
+ setBooleanOverride("projectAgentBrowserAccessOverrides", enabled);
+ const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
const projectNameEditedRef = useRef(false);
- const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
- onCopy: ({ path }) => {
- toastManager.add({ type: "success", title: "Path copied", description: path });
- },
- onError: (error) => {
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Failed to copy path",
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- },
- });
const faviconPath = representative.faviconPath ?? null;
const projectIcon = representative.projectIcon ?? null;
@@ -355,14 +493,6 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
? window.desktopBridge?.pickProjectFavicon
: undefined;
- const threadCountByMember = useMemo(() => {
- const counts = new Map<string, number>();
- for (const thread of threads) {
- const key = `${thread.environmentId}:${thread.projectId}`;
- counts.set(key, (counts.get(key) ?? 0) + 1);
- }
- return counts;
- }, [threads]);
const reportFailure = useCallback((title: string, result: AtomCommandResult<void, unknown>) => {
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
@@ -437,7 +567,25 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
// ----- default model -----
const storedSelection = representative.defaultModelSelection;
- const resolvedSelection = resolveDefaultProviderModelSelection(serverProviders, storedSelection);
+ const resolvedSelection = resolveDefaultProviderModelSelection(
+ serverProviders,
+ storedSelection ?? projectSettings.defaultModelSelection,
+ );
+ const mixedModel = group.memberProjects.some((member) => {
+ const config = environmentById.get(member.environmentId)?.serverConfig;
+ return (
+ !Equal.equals(member.defaultModelSelection, storedSelection) ||
+ (config !== null &&
+ config !== undefined &&
+ environmentById.get(representative.environmentId)?.serverConfig != null &&
+ JSON.stringify(
+ resolveDefaultProviderModelSelection(
+ config.providers,
+ member.defaultModelSelection ?? config.settings.defaultModelSelection,
+ ),
+ ) !== JSON.stringify(resolvedSelection))
+ );
+ });
const resolvedInstanceId = resolvedSelection?.instanceId ?? null;
const resolvedModel = resolvedSelection?.model ?? null;
const instanceEntries = useMemo(
@@ -461,14 +609,45 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
[resolvedInstanceId, resolvedModel, serverProviders, projectSettings],
);
const activeEntry = instanceEntries.find((entry) => entry.instanceId === resolvedInstanceId);
- const setDefaultModel = useCallback(
- (selection: ModelSelection | null) =>
- void updateAllMembers({ defaultModelSelection: selection }, "Failed to update default model"),
- [updateAllMembers],
- );
+ const setDefaultModel = (selection: ModelSelection | null) => {
+ if (selection !== null) {
+ for (const member of group.memberProjects) {
+ const environment = environmentById.get(member.environmentId);
+ const config = environment?.serverConfig;
+ const entry = config
+ ? applyProviderInstanceSettings(
+ deriveProviderInstanceEntries(config.providers),
+ config.settings,
+ ).find((candidate) => candidate.instanceId === selection.instanceId)
+ : undefined;
+ const options = config
+ ? getCustomModelOptionsByInstance(
+ { ...projectSettings, ...config.settings },
+ config.providers,
+ ).get(selection.instanceId)
+ : undefined;
+ if (
+ !entry?.enabled ||
+ !entry.isAvailable ||
+ !options?.some((model) => model.slug === selection.model && !model.isUnavailable)
+ ) {
+ toastManager.add({
+ type: "warning",
+ title: "Project model not saved",
+ description: `This model is unavailable on ${environment?.label ?? "a selected machine"}. Select a machine to choose its model separately.`,
+ });
+ return;
+ }
+ }
+ }
+ void updateAllMembers({ defaultModelSelection: selection }, "Failed to update default model");
+ };
// ----- new-thread workspace mode -----
const storedEnvMode = representative.defaultThreadEnvMode ?? null;
+ const mixedWorkspace = group.memberProjects.some(
+ (member) => member.defaultThreadEnvMode !== storedEnvMode,
+ );
const setDefaultThreadEnvMode = useCallback(
(mode: ThreadEnvMode | null) =>
void updateAllMembers(
@@ -478,12 +657,24 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
[updateAllMembers],
);
- const autoPull = representative.autoPull ?? false;
- const setAutoPull = useCallback(
- (enabled: boolean) =>
- void updateAllMembers({ autoPull: enabled }, "Failed to update automatic pull setting"),
- [updateAllMembers],
+ const autoPull = resolveProjectAutoPull(
+ projectSettings,
+ representative.id,
+ representative.autoPull,
);
+ const autoPullOverridden = group.memberProjects.some(
+ (member) =>
+ member.autoPull ||
+ environmentById.get(member.environmentId)?.serverConfig?.settings.projectAutoPullOverrides[
+ member.id
+ ] !== undefined,
+ );
+ const mixedAutoPull = group.memberProjects.some((member) => {
+ const settings = environmentById.get(member.environmentId)?.serverConfig?.settings;
+ return settings && resolveProjectAutoPull(settings, member.id, member.autoPull) !== autoPull;
+ });
+ const setAutoPull = (enabled: boolean | undefined) =>
+ setBooleanOverride("projectAutoPullOverrides", enabled);
// ----- project icon -----
const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);
@@ -506,27 +697,39 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
);
// ----- checkout selection and scripts -----
- const [selectedCheckoutKey, setSelectedCheckoutKey] = useState(representative.physicalProjectKey);
- const selectedCheckout =
- group.memberProjects.find((member) => member.physicalProjectKey === selectedCheckoutKey) ??
- representative;
+ const hasMultipleCheckouts = group.memberProjects.length > 1;
+ const [selectedCheckoutKey, setSelectedCheckoutKey] = useState<string | null>(null);
+ const selectedCheckoutMatch = group.memberProjects.find(
+ (member) => member.physicalProjectKey === selectedCheckoutKey,
+ );
+ const selectedCheckout = selectedCheckoutMatch ?? representative;
const selectedServerConfig = useAtomValue(
serverEnvironment.configValueAtom(selectedCheckout.environmentId),
);
const keybindings = selectedServerConfig?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
- const scripts = selectedCheckout.scripts;
+ const scriptSettings = useEnvironmentSettings(selectedCheckout.environmentId);
+ const scripts = resolveProjectScripts(scriptSettings, selectedCheckout);
+ const scriptsInherited = projectScriptsInheritDefaults(scriptSettings, selectedCheckout);
const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
- // Script writes replace the whole array, so two overlapping writes computed
- // from the same snapshot would drop each other's changes. One at a time.
- const [isSavingScripts, setIsSavingScripts] = useState(false);
- const savingScriptsRef = useRef(false);
+ const {
+ saving: isSavingScripts,
+ persist: persistScripts,
+ submit: submitScript,
+ } = useProjectScriptSettings([
+ {
+ environmentId: selectedCheckout.environmentId,
+ settings: scriptSettings,
+ keybindings,
+ project: selectedCheckout,
+ },
+ ]);
const t3File = useT3ProjectFileState(
selectedCheckout.environmentId,
selectedCheckout.workspaceRoot,
);
// What the "Default" option resolves to while no override is set: the
// repo's t3.json value when present, otherwise the global setting.
- const inheritedEnvMode = t3File.file?.defaultThreadEnvMode ?? settings.defaultThreadEnvMode;
+ const inheritedEnvMode = t3File.file?.defaultThreadEnvMode ?? scriptSettings.defaultThreadEnvMode;
const inheritedEnvModeSource = t3File.file?.defaultThreadEnvMode != null ? "t3.json" : "global";
const importableScripts = useMemo(
() =>
@@ -541,135 +744,12 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
[scripts, t3File.scripts],
);
- const persistScripts = useCallback(
- async (
- nextScripts: ReadonlyArray<ReturnType<typeof buildProjectScript>>,
- keybinding: string | null | undefined,
- keybindingCommand: ReturnType<typeof commandForProjectScript>,
- ): Promise<AtomCommandResult<void, unknown>> => {
- if (savingScriptsRef.current) {
- return AsyncResult.failure(
- Cause.fail(new Error("Another script change is still saving. Try again.")),
- );
- }
- savingScriptsRef.current = true;
- setIsSavingScripts(true);
- try {
- // Captured before the write so a cleared or deleted binding can be
- // removed from the keybindings config afterwards.
- const previousKeybinding = keybindingValueForCommand(keybindings, keybindingCommand);
- const updateResult = mapAtomCommandResult(
- await updateProject({
- environmentId: selectedCheckout.environmentId,
- input: { projectId: selectedCheckout.id, scripts: nextScripts },
- }),
- () => undefined,
- );
- if (updateResult._tag === "Failure") {
- reportFailure("Failed to save scripts", updateResult);
- return updateResult;
- }
-
- const keybindingRule = decodeProjectScriptKeybindingRule({
- keybinding,
- command: keybindingCommand,
- });
- if (!isElectron) return updateResult;
- const environmentIds = [selectedCheckout.environmentId];
- const previousTarget = previousKeybinding
- ? decodeProjectScriptKeybindingRule({
- keybinding: previousKeybinding,
- command: keybindingCommand,
- })
- : null;
- if (keybindingRule) {
- // `replace` swaps the command's previous rule instead of appending a
- // second one that would keep the old shortcut alive.
- const input =
- previousTarget && previousTarget.key !== keybindingRule.key
- ? { ...keybindingRule, replace: previousTarget }
- : keybindingRule;
- for (const environmentId of environmentIds) {
- const result = mapAtomCommandResult(
- await upsertKeybinding({ environmentId, input }),
- () => undefined,
- );
- if (result._tag === "Failure") {
- reportFailure("Failed to save keybinding", result);
- return result;
- }
- }
- } else if (previousTarget) {
- for (const environmentId of environmentIds) {
- const result = mapAtomCommandResult(
- await removeKeybinding({ environmentId, input: previousTarget }),
- () => undefined,
- );
- if (result._tag === "Failure") {
- reportFailure("Failed to remove keybinding", result);
- return result;
- }
- }
- }
- return updateResult;
- } finally {
- savingScriptsRef.current = false;
- setIsSavingScripts(false);
- }
- },
- [
- keybindings,
- removeKeybinding,
- reportFailure,
- selectedCheckout.environmentId,
- selectedCheckout.id,
- updateProject,
- upsertKeybinding,
- ],
- );
-
- const submitScript = useCallback(
- async (
- scriptId: string | null,
- input: NewProjectScriptInput,
- ): Promise<AtomCommandResult<void, unknown>> => {
- if (scriptId === null) {
- const nextId = nextProjectScriptId(
- input.name,
- scripts.map((script) => script.id),
- );
- const nextScript = buildProjectScript(nextId, input);
- const nextScripts = input.runOnWorktreeCreate
- ? [
- ...scripts.map((script) =>
- script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
- ),
- nextScript,
- ]
- : [...scripts, nextScript];
- return persistScripts(nextScripts, input.keybinding, commandForProjectScript(nextId));
- }
-
- const updatedScript = buildProjectScript(scriptId, input);
- const nextScripts = scripts.map((script) =>
- script.id === scriptId
- ? updatedScript
- : input.runOnWorktreeCreate
- ? { ...script, runOnWorktreeCreate: false }
- : script,
- );
- return persistScripts(nextScripts, input.keybinding, commandForProjectScript(scriptId));
- },
- [persistScripts, scripts],
- );
-
- const deleteScript = useCallback(
- (scriptId: string) => {
- const nextScripts = scripts.filter((script) => script.id !== scriptId);
- void persistScripts(nextScripts, null, commandForProjectScript(scriptId));
- },
- [persistScripts, scripts],
- );
+ const deleteScript = (scriptId: string) =>
+ void persistScripts(
+ (current) => current.filter((script) => script.id !== scriptId),
+ scriptId,
+ null,
+ );
const importFileScript = useCallback(
async (fileScript: T3ProjectFileScript) => {
@@ -692,7 +772,7 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
});
}
},
- [submitScript],
+ [submitScript, setEditorRequest],
);
// ----- checkouts -----
@@ -720,14 +800,15 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
memberKeys.has(`${thread.environmentId}:${thread.projectId}`),
);
const isWholeGroup = members.length === group.memberProjects.length;
+ const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project";
const singleMember = members.length === 1 ? members[0]! : null;
const targetLabel = singleMember?.title ?? group.displayName;
const confirmed = await settlePromise(() =>
api.dialogs.confirm(
[
projectThreads.length > 0
- ? `Remove project "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`
- : `Remove project "${targetLabel}"?`,
+ ? `Remove ${targetKind} "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`
+ : `Remove ${targetKind} "${targetLabel}"?`,
...(singleMember
? [
`Path: ${singleMember.workspaceRoot}`,
@@ -741,7 +822,7 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
"This permanently clears conversation history for those threads and any archived threads.",
]
: ["This permanently clears any archived conversation history."]),
- isWholeGroup
+ isWholeGroup && !hasOtherMembers
? "This removes only the project entries, not the files on disk."
: "Other entries in this grouped project are unaffected.",
"This action cannot be undone.",
@@ -783,33 +864,50 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
draftStore.clearProjectDraftThreadId(projectRef);
}
- // The project's settings page just deleted itself; there is no projects
- // listing to fall back to, so leave settings entirely.
if (isWholeGroup) {
- void navigate({ to: "/", replace: true });
+ if (hasOtherMembers) {
+ void navigate({
+ to: "/settings/projects",
+ search: { project: group.projectKey, machine: undefined },
+ replace: true,
+ });
+ } else {
+ void navigate({ to: "/", replace: true });
+ }
}
},
[
deleteProject,
group.displayName,
group.memberProjects.length,
+ group.projectKey,
+ hasOtherMembers,
navigate,
reportFailure,
threads,
],
);
- const selectedCheckoutThreadCount = threadCountByMember.get(memberKey(selectedCheckout)) ?? 0;
const selectedCheckoutGrouping =
projectGroupingSettings.sidebarProjectGroupingOverrides?.[
deriveProjectGroupingOverrideKey(selectedCheckout)
] ?? "inherit";
- const selectedCheckoutLabel = selectedCheckout.environmentLabel ?? "This machine";
+ const checkoutLabel = (member: SidebarProjectGroupMember) => {
+ const label = member.environmentLabel ?? "This machine";
+ return group.memberProjects.some(
+ (other) =>
+ other.physicalProjectKey !== member.physicalProjectKey &&
+ (other.environmentLabel ?? "This machine") === label,
+ )
+ ? `${label} · ${member.workspaceRoot}`
+ : label;
+ };
+ const selectedCheckoutLabel = checkoutLabel(selectedCheckout);
return (
<>
- <SettingsPageContainer width="wide" className="gap-8">
- <SettingsSection title="Project">
+ <SettingsPageContainer className="gap-6">
+ <SettingsSection title="Project" hideTitle>
<SettingsRow
title="Name"
description="The shared name for this project group in the sidebar and thread lists."
@@ -887,11 +985,23 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
/>
<SettingsRow
title="Model"
- description="New threads in this project start with this model. Applies to every checkout in this group."
+ status={
+ mixedModel
+ ? "Mixed defaults or overrides. Choosing a model updates all selected checkouts."
+ : storedSelection === null
+ ? "Inherited"
+ : "Overridden"
+ }
+ description={
+ storedSelection === null
+ ? "Inherited from machine defaults. New threads use the default model."
+ : "Overridden for this project. Reset to use the default model."
+ }
resetAction={
- storedSelection !== null ? (
+ group.memberProjects.some((member) => member.defaultModelSelection !== null) ? (
<SettingResetButton
label="project default model"
+ tooltip="Reset to inherited model"
onClick={() => setDefaultModel(null)}
/>
) : null
@@ -946,11 +1056,23 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
/>
<SettingsRow
title="Workspace"
- description="Where new threads in this project start. Overrides t3.json and the global default; applies to every checkout in this group."
+ status={
+ mixedWorkspace
+ ? "Mixed overrides. Choosing a workspace updates all selected checkouts."
+ : storedEnvMode === null
+ ? "Inherited"
+ : "Overridden"
+ }
+ description={
+ storedEnvMode === null
+ ? "Inherited from t3.json or machine defaults."
+ : "Overridden for this project. Reset to inherit its workspace default."
+ }
resetAction={
- storedEnvMode !== null ? (
+ group.memberProjects.some((member) => member.defaultThreadEnvMode !== null) ? (
<SettingResetButton
label="project workspace default"
+ tooltip="Reset to inherited workspace"
onClick={() => setDefaultThreadEnvMode(null)}
/>
) : null
@@ -990,79 +1112,130 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
<SettingsRow
title="Automatically pull"
description="Keeps the default branch current in the background when the checkout has no local changes or commits."
+ status={
+ mixedAutoPull
+ ? "Mixed"
+ : autoPullOverridden
+ ? "Overridden"
+ : `Inherited (${autoPull ? "on" : "off"})`
+ }
resetAction={
- autoPull ? (
- <SettingResetButton label="automatic pull" onClick={() => setAutoPull(false)} />
+ autoPullOverridden ? (
+ <SettingResetButton
+ label="automatic pull"
+ tooltip="Reset to inherited automatic pull setting"
+ disabled={savingBrowserAccess}
+ onClick={() => void setAutoPull(undefined)}
+ />
) : null
}
control={
<Switch
checked={autoPull}
+ disabled={savingBrowserAccess}
aria-label="Automatically pull the default branch"
- onCheckedChange={setAutoPull}
+ onCheckedChange={(enabled) => void setAutoPull(enabled)}
/>
}
/>
+ <SettingsRow
+ title="Agent browser access"
+ description={
+ browserMixed
+ ? "Mixed defaults or overrides across selected checkouts."
+ : browserOverride === undefined
+ ? "Inherited from machine defaults. Controls agent access to the preview browser."
+ : "Overridden for this project. Applies when the agent session next starts."
+ }
+ resetAction={
+ browserOverrides.some((value) => value !== undefined) ? (
+ <SettingResetButton
+ label="project browser access"
+ tooltip="Reset to inherited browser access"
+ disabled={savingBrowserAccess}
+ onClick={() => void setBrowserAccess(undefined)}
+ />
+ ) : null
+ }
+ control={
+ <Select
+ value={
+ browserMixed
+ ? "mixed"
+ : browserOverride === undefined
+ ? "inherit"
+ : browserOverride
+ ? "enabled"
+ : "disabled"
+ }
+ disabled={savingBrowserAccess}
+ onValueChange={(value) => {
+ if (value === "inherit") void setBrowserAccess(undefined);
+ else if (value === "enabled" || value === "disabled")
+ void setBrowserAccess(value === "enabled");
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Project agent browser access">
+ <SelectValue>
+ {browserMixed
+ ? "Mixed"
+ : browserOverride === undefined
+ ? `Inherit (${projectSettings.enableAgentBrowserAccess ? "on" : "off"})`
+ : browserOverride
+ ? "On"
+ : "Off"}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="inherit">Inherit defaults</SelectItem>
+ <SelectItem value="enabled">On</SelectItem>
+ <SelectItem value="disabled">Off</SelectItem>
+ </SelectPopup>
+ </Select>
+ }
+ />
</SettingsSection>
- <SettingsSection
- title="Checkout"
- headerAction={
- <Select
- value={selectedCheckout.physicalProjectKey}
- onValueChange={(value) => setSelectedCheckoutKey(String(value))}
- >
- <SelectTrigger size="sm" className="max-w-64" aria-label="Selected checkout">
- <SelectValue>{selectedCheckoutLabel}</SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- {group.memberProjects.map((member) => (
- <SelectItem
- key={member.physicalProjectKey}
- hideIndicator
- value={member.physicalProjectKey}
- >
- {member.environmentLabel ?? "This machine"} · {member.workspaceRoot}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- }
- >
- <div className="px-3 py-2 sm:px-4">
- <div className="flex min-w-0 items-center rounded-lg bg-muted/30 p-1 text-base text-muted-foreground sm:text-sm">
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- aria-label="Copy checkout path"
- className="group flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-left outline-none hover:bg-accent/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
- type="button"
- onClick={() =>
- copyPathToClipboard(selectedCheckout.workspaceRoot, {
- path: selectedCheckout.workspaceRoot,
- })
- }
- >
- <code className="min-w-0 flex-1 truncate font-mono">
- {selectedCheckout.workspaceRoot}
- </code>
- <CopyIcon className="size-4 shrink-0 opacity-60 group-hover:opacity-100" />
- </button>
- }
- />
- <TooltipPopup side="top">Copy path</TooltipPopup>
- </Tooltip>
- <div className="shrink-0 border-l border-border/60 px-2 tabular-nums">
- {selectedCheckoutThreadCount === 1
- ? "1 thread"
- : `${selectedCheckoutThreadCount} threads`}
- </div>
- </div>
- </div>
+ <SettingsSection title="Checkout">
+ {hasMultipleCheckouts ? (
+ <SettingsRow
+ title="Checkout"
+ description="Actions and grouping belong to this checkout."
+ control={
+ <Select
+ value={selectedCheckout.physicalProjectKey}
+ onValueChange={(value) => {
+ if (value) setSelectedCheckoutKey(value);
+ }}
+ >
+ <SelectTrigger size="sm" aria-label="Checkout">
+ <SelectValue className="max-w-96 truncate">{selectedCheckoutLabel}</SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ {group.memberProjects.map((member) => (
+ <SelectItem key={member.physicalProjectKey} value={member.physicalProjectKey}>
+ <span className="max-w-96 whitespace-normal break-all">
+ {checkoutLabel(member)}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ }
+ />
+ ) : null}
<SettingsRow
title="Project grouping"
description="How this checkout joins project groups in the sidebar. Changing it can move you to a different project group."
+ resetAction={
+ selectedCheckoutGrouping !== "inherit" ? (
+ <SettingResetButton
+ label="project grouping"
+ tooltip="Reset to inherited project grouping"
+ onClick={() => updateGroupingPreference(selectedCheckout, "inherit")}
+ />
+ ) : null
+ }
control={
<Select
value={selectedCheckoutGrouping}
@@ -1121,10 +1294,20 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
<div className="min-w-0">
<h3 className="text-base font-semibold text-foreground">Actions</h3>
<p className="text-pretty text-sm text-muted-foreground">
- Saved and run only in {selectedCheckoutLabel}.
+ {scriptsInherited
+ ? "Inherited from machine defaults."
+ : `Overridden for ${selectedCheckoutLabel}.`}
</p>
</div>
<div className="flex w-full flex-wrap gap-1.5 sm:w-auto sm:shrink-0 sm:justify-end">
+ {!scriptsInherited ? (
+ <SettingResetButton
+ label="project actions"
+ tooltip="Reset to inherited actions"
+ disabled={isSavingScripts}
+ onClick={() => void persistScripts(() => null)}
+ />
+ ) : null}
{importableScripts.length > 0 ? (
<Menu>
<MenuTrigger
@@ -1173,65 +1356,12 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
</Button>
</div>
</div>
- {scripts.length === 0 ? (
- <p className="px-3 py-2 text-base text-muted-foreground sm:px-4 sm:text-sm">
- No actions configured for this checkout.
- </p>
- ) : (
- scripts.map((script) => {
- const shortcutLabel = shortcutLabelForCommand(
- keybindings,
- commandForProjectScript(script.id),
- );
- return (
- <SettingsRow
- key={script.id}
- className="group py-2"
- title={
- <span className="flex min-w-0 items-center gap-2">
- <ScriptIcon
- icon={script.icon}
- className="size-4 shrink-0 text-muted-foreground"
- />
- <span className="min-w-0 truncate">{script.name}</span>
- {script.runOnWorktreeCreate ? (
- <span className="shrink-0 rounded-sm border border-border/60 px-1.5 py-px text-[11px] font-normal text-muted-foreground">
- setup
- </span>
- ) : null}
- {script.previewUrl ? (
- <span className="shrink-0 rounded-sm border border-border/60 px-1.5 py-px text-[11px] font-normal text-muted-foreground max-sm:hidden">
- preview · desktop only
- </span>
- ) : null}
- </span>
- }
- description={
- <code className="block max-w-full truncate font-mono">{script.command}</code>
- }
- control={
- <>
- {shortcutLabel ? (
- <span className="text-xs text-muted-foreground">{shortcutLabel}</span>
- ) : null}
- <Button
- size="icon-xs"
- variant="ghost"
- className="shrink-0 text-muted-foreground opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"
- aria-label={`Edit ${script.name}`}
- disabled={isSavingScripts}
- onClick={() =>
- setEditorRequest(editorRequestForScript(script, keybindings))
- }
- >
- <SettingsIcon className="size-3.5" />
- </Button>
- </>
- }
- />
- );
- })
- )}
+ <ProjectActionsList
+ scripts={scripts}
+ keybindings={keybindings}
+ disabled={isSavingScripts}
+ onEdit={(script) => setEditorRequest(editorRequestForScript(script, keybindings))}
+ />
{t3File.status === "invalid" ? (
<SettingsRow
title="t3.json is invalid"
@@ -1244,12 +1374,18 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
<SettingsSection title="Danger">
<SettingsRow
title={
- group.memberProjects.length > 1 ? "Remove this project everywhere" : "Remove project"
+ hasOtherMembers
+ ? "Remove checkout"
+ : group.memberProjects.length > 1
+ ? "Remove this project everywhere"
+ : "Remove project"
}
description={
- group.memberProjects.length > 1
- ? `Deletes all ${group.memberProjects.length} checkout entries and their threads on every machine. Files on disk are not touched.`
- : "Deletes the project entry and its threads. Files on disk are not touched."
+ hasOtherMembers
+ ? "Deletes the selected machine's checkout entries and their threads. Other machines and files on disk are not touched."
+ : group.memberProjects.length > 1
+ ? `Deletes all ${group.memberProjects.length} checkout entries and their threads on every machine. Files on disk are not touched.`
+ : "Deletes the project entry and its threads. Files on disk are not touched."
}
control={
<Button
@@ -1258,7 +1394,11 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
onClick={() => void removeMembers(group.memberProjects)}
>
<Trash2Icon />
- {group.memberProjects.length > 1 ? "Remove all entries" : "Remove project"}
+ {hasOtherMembers
+ ? "Remove checkout"
+ : group.memberProjects.length > 1
+ ? "Remove all entries"
+ : "Remove project"}
</Button>
}
/>
diff --git a/apps/web/src/components/settings/ProjectsSettings.tsx b/apps/web/src/components/settings/ProjectsSettings.tsx
new file mode 100644
index 00000000000..4eedaab6384
--- /dev/null
+++ b/apps/web/src/components/settings/ProjectsSettings.tsx
@@ -0,0 +1,160 @@
+import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
+import { FolderIcon } from "lucide-react";
+import type { ReactNode } from "react";
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
+import { ProjectFavicon } from "../ProjectFavicon";
+import { WorkspacePageContainer } from "../WorkspacePageContainer";
+import { useEnvironments } from "../../state/environments";
+import { Toggle, ToggleGroup } from "../ui/toggle-group";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { ProjectSettingsPanel, useSettingsProjectGroups } from "./ProjectSettingsPanel";
+import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
+
+function ScopePicker({
+ label,
+ value,
+ options,
+ onChange,
+}: {
+ label: "project" | "machine";
+ value: string | null;
+ options: ReadonlyArray<{ value: string; label: string; icon?: ReactNode }>;
+ onChange: (value: string | null) => void;
+}) {
+ const selected = options.find((option) => option.value === value);
+ const allIcon =
+ label === "project" ? <FolderIcon aria-hidden className="size-3.5 shrink-0" /> : null;
+ return (
+ <Select
+ value={value ?? "all"}
+ onValueChange={(next) => {
+ if (next) onChange(next === "all" ? null : next);
+ }}
+ >
+ <SelectTrigger
+ size="compact"
+ aria-label={`${label === "project" ? "Project" : "Machine"} scope`}
+ className="w-auto min-w-0 max-w-52"
+ >
+ <SelectValue className="flex min-w-0 items-center gap-1.5">
+ {value === null ? allIcon : selected?.icon}
+ <span className="truncate">
+ {value === null ? `All ${label}s` : (selected?.label ?? `Unavailable ${label}`)}
+ </span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="start" alignItemWithTrigger={false}>
+ <SelectItem value="all">
+ <span className="flex items-center gap-2">
+ {allIcon}All {label}s
+ </span>
+ </SelectItem>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ <span className="flex items-center gap-2">
+ {option.icon}
+ {option.label}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ );
+}
+
+export function ProjectsSettings({
+ projectKey,
+ machineId,
+ onScopeChange,
+}: {
+ projectKey: string | null;
+ machineId: string | null;
+ onScopeChange: (project: string | null, machine: string | null) => void;
+}) {
+ const groups = useSettingsProjectGroups();
+ const { environments } = useEnvironments();
+ const machine = environments.find((environment) => environment.environmentId === machineId);
+ const machineOptions = environments.map((environment) => ({
+ value: environment.environmentId,
+ label: environment.label,
+ icon: (
+ <EnvironmentMachineIcon
+ aria-hidden
+ kind={resolveEnvironmentMachineKind(environment.serverConfig)}
+ className="size-3.5 shrink-0"
+ />
+ ),
+ }));
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="scrollbar-gutter-both shrink-0 overflow-y-auto">
+ <WorkspacePageContainer className="pb-0">
+ <div
+ className="flex flex-wrap items-center gap-2"
+ role="group"
+ aria-label="Settings scope"
+ >
+ {environments.length > 3 ? (
+ <ScopePicker
+ label="machine"
+ value={machineId}
+ options={machineOptions}
+ onChange={(value) => onScopeChange(projectKey, value)}
+ />
+ ) : (
+ <ToggleGroup
+ aria-label="Machine scope"
+ variant="segmented"
+ className="max-w-full flex-wrap"
+ value={[machineId ?? "all"]}
+ onValueChange={(next) => {
+ const value = next[0];
+ if (value) onScopeChange(projectKey, value === "all" ? null : value);
+ }}
+ >
+ <Toggle value="all">All machines</Toggle>
+ {machineOptions.map((option) => (
+ <Toggle key={option.value} value={option.value} title={option.label}>
+ {option.icon}
+ <span className="max-w-36 truncate">{option.label}</span>
+ </Toggle>
+ ))}
+ </ToggleGroup>
+ )}
+ <div className="ms-auto">
+ <ScopePicker
+ label="project"
+ value={projectKey}
+ options={groups.map((group) => ({
+ value: group.projectKey,
+ label: group.displayName,
+ icon: (
+ <ProjectFavicon
+ environmentId={group.environmentId}
+ cwd={group.workspaceRoot}
+ projectName={group.title}
+ faviconPath={group.faviconPath}
+ projectIcon={group.projectIcon}
+ className="size-3.5"
+ />
+ ),
+ }))}
+ onChange={(value) => onScopeChange(value, machineId)}
+ />
+ </div>
+ </div>
+ </WorkspacePageContainer>
+ </div>
+ {machineId !== null && !machine ? (
+ <p className="p-8 text-sm text-muted-foreground">This machine is no longer available.</p>
+ ) : projectKey === null ? (
+ <ProjectDefaultsSettings environmentId={machine?.environmentId ?? null} />
+ ) : (
+ <ProjectSettingsPanel
+ projectKey={projectKey}
+ environmentId={machine?.environmentId ?? null}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index fe782c5757d..c3d5d7ba812 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -2557,55 +2557,24 @@ export function GeneralSettingsPanel() {
<SettingsSection id="projects-and-threads" title="Projects & threads">
<SettingsRow
- serverScoped
{...searchableSetting("new-threads")}
- description="Pick the default workspace mode for newly created draft threads."
- resetAction={
- settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ||
- settings.newWorktreesStartFromOrigin !==
- DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin ? (
- <SettingResetButton
- label="new threads"
- onClick={() =>
- updateSettings({
- defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
- newWorktreesStartFromOrigin:
- DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
- })
- }
- />
- ) : null
- }
+ description="Choose the default model and workspace for all projects or a specific project."
control={
- <Select
- value={settings.defaultThreadEnvMode}
- onValueChange={(value) => {
- if (value === "local" || value === "worktree") {
- updateSettings({ defaultThreadEnvMode: value });
- }
- }}
+ <Button
+ render={
+ <Link to="/settings/projects" search={{ project: undefined, machine: undefined }} />
+ }
+ size="sm"
+ variant="outline"
>
- <SelectTrigger size="sm" className="w-full sm:w-44" aria-label="Default thread mode">
- <SelectValue>
- {settings.defaultThreadEnvMode === "worktree" ? "New worktree" : "Local"}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- <SelectItem hideIndicator value="local">
- Local
- </SelectItem>
- <SelectItem hideIndicator value="worktree">
- New worktree
- </SelectItem>
- </SelectPopup>
- </Select>
+ Project settings
+ </Button>
}
/>
<SettingsRow
serverScoped
- className="bg-muted/20 sm:pl-9"
- title={searchableSetting("start-from-origin").title}
+ {...searchableSetting("start-from-origin")}
description="Creates the worktree from the latest matching branch on origin instead of your local branch."
resetAction={
settings.newWorktreesStartFromOrigin !==
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index 0e1ff2076e9..9547a14c8bd 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -15,6 +15,7 @@ import {
BlocksIcon,
BotIcon,
GitBranchIcon,
+ PanelsTopLeftIcon,
KeyboardIcon,
Link2Icon,
PaletteIcon,
@@ -72,6 +73,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
> = {
"/settings/general": Settings2Icon,
"/settings/appearance": PaletteIcon,
+ "/settings/projects": PanelsTopLeftIcon,
"/settings/keybindings": KeyboardIcon,
"/settings/providers": BotIcon,
"/settings/integrations": BlocksIcon,
@@ -274,12 +276,18 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
setOpenMobile(false);
}
const targetId = item.targetId ?? item.id;
- if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
+ if (
+ item.to !== "/settings/projects" &&
+ pathname === item.to &&
+ currentHash.replace(/^#/, "") === targetId
+ ) {
scrollToSettingsTarget(targetId);
return;
}
void navigate({
to: item.to,
+ search: (previous) =>
+ item.to === "/settings/projects" ? { ...previous, project: undefined } : previous,
hash: targetId,
replace: true,
hashScrollIntoView: false,
diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx
index 82fbed96459..1bfa8c87146 100644
--- a/apps/web/src/components/settings/settingsLayout.tsx
+++ b/apps/web/src/components/settings/settingsLayout.tsx
@@ -284,7 +284,11 @@ export function SettingsRow({
ref={targetRef}
tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
data-slot="settings-row"
- className={cn("rounded-xl px-3 sm:px-4", children ? "pt-3 pb-1" : "py-3", className)}
+ className={cn(
+ "rounded-xl px-3 sm:px-4 aria-disabled:opacity-50 aria-disabled:[&_*]:text-muted-foreground",
+ children ? "pt-3 pb-1" : "py-3",
+ className,
+ )}
>
<div className="flex flex-col gap-3 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] sm:items-center sm:gap-8">
<div className="min-w-0 flex-1 space-y-1">
@@ -320,10 +324,12 @@ export function SettingsRow({
export function SettingResetButton({
label,
+ tooltip = "Reset to default",
disabled = false,
onClick,
}: {
label: string;
+ tooltip?: string;
disabled?: boolean;
onClick: () => void;
}) {
@@ -345,7 +351,7 @@ export function SettingResetButton({
</Button>
}
/>
- <TooltipPopup side="top">Reset to default</TooltipPopup>
+ <TooltipPopup side="top">{tooltip}</TooltipPopup>
</Tooltip>
);
}
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 7358ed8f9a1..f715f6ca4e6 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -2,6 +2,7 @@ import { isElectron } from "~/env";
import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils";
export type SettingsPath =
+ | "/settings/projects"
| "/settings/general"
| "/settings/appearance"
| "/settings/keybindings"
@@ -49,6 +50,7 @@ export interface SettingsSearchAvailability {
export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/general": "General",
"/settings/appearance": "Appearance",
+ "/settings/projects": "Projects",
"/settings/keybindings": "Keybindings",
"/settings/providers": "Providers",
"/settings/integrations": "Integrations",
@@ -63,6 +65,14 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
* that may not be mounted point at their nearest stable section instead.
*/
export const SETTINGS_SEARCH_ITEMS = [
+ {
+ id: "project-defaults",
+ title: "Project defaults and overrides",
+ to: "/settings/projects",
+ searchTerms: [
+ "model workspace browser machines projects inheritance automatic pull checkout grouping actions scripts",
+ ],
+ },
{
id: "color-scheme",
title: "Color scheme",
@@ -235,14 +245,13 @@ export const SETTINGS_SEARCH_ITEMS = [
{
id: "new-threads",
title: "New threads",
- to: "/settings/general",
+ to: "/settings/projects",
searchTerms: ["default workspace mode draft local worktree"],
},
{
id: "start-from-origin",
title: "Start from origin",
to: "/settings/general",
- targetId: "new-threads",
searchTerms: ["new worktrees latest matching remote branch local"],
},
{
@@ -345,7 +354,7 @@ export const SETTINGS_SEARCH_ITEMS = [
{
id: "agent-browser-access",
title: "Agent browser access",
- to: "/settings/integrations",
+ to: "/settings/projects",
searchTerms: ["allow open drive preview tools sessions"],
},
{
diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts
index 91b757f51e0..afd503e63c2 100644
--- a/apps/web/src/hooks/useHandleNewThread.test.ts
+++ b/apps/web/src/hooks/useHandleNewThread.test.ts
@@ -49,14 +49,31 @@ const testState = vi.hoisted(() => {
});
vi.mock("@effect/atom-react", () => ({
- useAtomValue: () => ({ defaultThreadEnvMode: "local", newWorktreesStartFromOrigin: false }),
+ useAtomValue: (atom: unknown) =>
+ atom === "primary-settings"
+ ? { newWorktreesStartFromOrigin: false }
+ : new Map([
+ [
+ "environment-ssh",
+ {
+ settings: {
+ defaultThreadEnvMode: "local",
+ newWorktreesStartFromOrigin: false,
+ defaultModelSelection: null,
+ },
+ },
+ ],
+ ]),
}));
vi.mock("@t3tools/client-runtime/environment", () => ({
scopedProjectKey: () => "remote-project",
scopeProjectRef: (environmentId: string, projectId: string) => ({ environmentId, projectId }),
scopeThreadRef: (environmentId: string, threadId: string) => ({ environmentId, threadId }),
}));
-vi.mock("@t3tools/contracts", () => ({ DEFAULT_RUNTIME_MODE: "default" }));
+vi.mock("@t3tools/contracts", () => ({
+ DEFAULT_RUNTIME_MODE: "default",
+ DEFAULT_SERVER_SETTINGS: {},
+}));
vi.mock("@t3tools/shared/threadEnvMode", () => ({
resolveDefaultThreadEnvMode: (input: {
readonly projectFile: "local" | "worktree" | null;
@@ -113,7 +130,10 @@ vi.mock("../state/entities", () => ({
useProjects: () => [],
useThread: () => null,
}));
-vi.mock("../state/server", () => ({ primaryServerSettingsAtom: {} }));
+vi.mock("../state/server", () => ({
+ environmentServerConfigsAtom: {},
+ primaryServerSettingsAtom: "primary-settings",
+}));
vi.mock("../threadRoutes", () => ({ resolveThreadRouteTarget: () => null }));
vi.mock("../uiStateStore", () => ({
legacyProjectCwdPreferenceKey: () => "remote-project",
diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts
index c26b25d1316..78dfc1b13fe 100644
--- a/apps/web/src/hooks/useHandleNewThread.ts
+++ b/apps/web/src/hooks/useHandleNewThread.ts
@@ -4,7 +4,12 @@ import {
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
-import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts";
+import {
+ DEFAULT_RUNTIME_MODE,
+ DEFAULT_SERVER_SETTINGS,
+ type ScopedProjectRef,
+ type ThreadId,
+} from "@t3tools/contracts";
import { useParams, useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import {
@@ -30,7 +35,7 @@ import {
resolveNewThreadModelSelectionOverride,
} from "../lib/chatThreadActions";
import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults";
-import { primaryServerSettingsAtom } from "../state/server";
+import { environmentServerConfigsAtom, primaryServerSettingsAtom } from "../state/server";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useClientSettings } from "./useSettings";
@@ -55,11 +60,7 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
}
export function useNewThreadHandler() {
- // New-thread defaults are a user preference, and the settings UI only ever
- // edits the primary environment's settings.json. Reading the target
- // environment's own settings here would silently reset remote projects to
- // the decoded defaults ("local" mode, current branch), since nothing can
- // set those values on a remote server.
+ const environmentServerConfigs = useAtomValue(environmentServerConfigsAtom);
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const router = useRouter();
@@ -83,6 +84,8 @@ export function useNewThreadHandler() {
// up again and finding whichever draft it happens to hold.
): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
const projects = readProjects();
+ const targetServerSettings =
+ environmentServerConfigs.get(projectRef.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS;
const {
getComposerDraft,
getDraftSessionByLogicalProjectKey,
@@ -138,7 +141,8 @@ export function useNewThreadHandler() {
);
const resolveModelSelectionOverride = (destinationDraftId: DraftId) =>
resolveNewThreadModelSelectionOverride({
- projectDefaultSelection: project?.defaultModelSelection ?? null,
+ projectDefaultSelection:
+ project?.defaultModelSelection ?? targetServerSettings.defaultModelSelection ?? null,
carrySelection: carryModelSelection,
carrySourceDraftId:
currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null,
@@ -157,7 +161,7 @@ export function useNewThreadHandler() {
project.workspaceRoot,
)
: null,
- globalDefault: primaryServerSettings.defaultThreadEnvMode,
+ globalDefault: targetServerSettings.defaultThreadEnvMode,
});
};
const logicalProjectKey = project
@@ -429,7 +433,13 @@ export function useNewThreadHandler() {
return { draftId, threadId };
})();
},
- [getCurrentRouteTarget, primaryServerSettings, projectGroupingSettings, router],
+ [
+ environmentServerConfigs,
+ getCurrentRouteTarget,
+ primaryServerSettings.newWorktreesStartFromOrigin,
+ projectGroupingSettings,
+ router,
+ ],
);
}
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index 5c796f3ab6c..b1a9d0b9e04 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -18,6 +18,7 @@ import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
+import { Route as SettingsProjectsRouteImport } from './routes/settings.projects'
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
import { Route as SettingsIntegrationsRouteImport } from './routes/settings.integrations'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
@@ -75,6 +76,11 @@ const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
path: '/providers',
getParentRoute: () => SettingsRoute,
} as any)
+const SettingsProjectsRoute = SettingsProjectsRouteImport.update({
+ id: '/projects',
+ path: '/projects',
+ getParentRoute: () => SettingsRoute,
+} as any)
const SettingsKeybindingsRoute = SettingsKeybindingsRouteImport.update({
id: '/keybindings',
path: '/keybindings',
@@ -154,6 +160,7 @@ export interface FileRoutesByFullPath {
'/settings/general': typeof SettingsGeneralRoute
'/settings/integrations': typeof SettingsIntegrationsRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
+ '/settings/projects': typeof SettingsProjectsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
@@ -175,6 +182,7 @@ export interface FileRoutesByTo {
'/settings/general': typeof SettingsGeneralRoute
'/settings/integrations': typeof SettingsIntegrationsRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
+ '/settings/projects': typeof SettingsProjectsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/': typeof ChatIndexRoute
@@ -199,6 +207,7 @@ export interface FileRoutesById {
'/settings/general': typeof SettingsGeneralRoute
'/settings/integrations': typeof SettingsIntegrationsRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
+ '/settings/projects': typeof SettingsProjectsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/_chat/': typeof ChatIndexRoute
@@ -224,6 +233,7 @@ export interface FileRouteTypes {
| '/settings/general'
| '/settings/integrations'
| '/settings/keybindings'
+ | '/settings/projects'
| '/settings/providers'
| '/settings/source-control'
| '/$environmentId/$threadId'
@@ -245,6 +255,7 @@ export interface FileRouteTypes {
| '/settings/general'
| '/settings/integrations'
| '/settings/keybindings'
+ | '/settings/projects'
| '/settings/providers'
| '/settings/source-control'
| '/'
@@ -268,6 +279,7 @@ export interface FileRouteTypes {
| '/settings/general'
| '/settings/integrations'
| '/settings/keybindings'
+ | '/settings/projects'
| '/settings/providers'
| '/settings/source-control'
| '/_chat/'
@@ -351,6 +363,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsProvidersRouteImport
parentRoute: typeof SettingsRoute
}
+ '/settings/projects': {
+ id: '/settings/projects'
+ path: '/projects'
+ fullPath: '/settings/projects'
+ preLoaderRoute: typeof SettingsProjectsRouteImport
+ parentRoute: typeof SettingsRoute
+ }
'/settings/keybindings': {
id: '/settings/keybindings'
path: '/keybindings'
@@ -462,6 +481,7 @@ interface SettingsRouteChildren {
SettingsGeneralRoute: typeof SettingsGeneralRoute
SettingsIntegrationsRoute: typeof SettingsIntegrationsRoute
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
+ SettingsProjectsRoute: typeof SettingsProjectsRoute
SettingsProvidersRoute: typeof SettingsProvidersRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
}
@@ -474,6 +494,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsGeneralRoute: SettingsGeneralRoute,
SettingsIntegrationsRoute: SettingsIntegrationsRoute,
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
+ SettingsProjectsRoute: SettingsProjectsRoute,
SettingsProvidersRoute: SettingsProvidersRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
}
diff --git a/apps/web/src/routes/projects.$projectKey.tsx b/apps/web/src/routes/projects.$projectKey.tsx
index 6ae03719c04..d636c0a953e 100644
--- a/apps/web/src/routes/projects.$projectKey.tsx
+++ b/apps/web/src/routes/projects.$projectKey.tsx
@@ -1,15 +1,17 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
-import { ProjectSettingsPage } from "../components/settings/ProjectSettingsPanel";
-
export const Route = createFileRoute("/projects/$projectKey")({
- beforeLoad: async ({ context }) => {
+ beforeLoad: async ({ context, params }) => {
if (
context.authGateState.status !== "authenticated" &&
context.authGateState.status !== "hosted-static"
) {
throw redirect({ to: "/pair", replace: true });
}
+ throw redirect({
+ to: "/settings/projects",
+ search: { project: params.projectKey, machine: undefined },
+ replace: true,
+ });
},
- component: () => <ProjectSettingsPage projectKey={Route.useParams().projectKey} />,
});
diff --git a/apps/web/src/routes/settings.projects.tsx b/apps/web/src/routes/settings.projects.tsx
new file mode 100644
index 00000000000..fa79f46fbb2
--- /dev/null
+++ b/apps/web/src/routes/settings.projects.tsx
@@ -0,0 +1,27 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { ProjectsSettings } from "../components/settings/ProjectsSettings";
+
+export const Route = createFileRoute("/settings/projects")({
+ validateSearch: (search: Record<string, unknown>) => ({
+ project: typeof search.project === "string" ? search.project : undefined,
+ machine: typeof search.machine === "string" ? search.machine : undefined,
+ }),
+ component: ProjectsRoute,
+});
+
+function ProjectsRoute() {
+ const { project, machine } = Route.useSearch();
+ const navigate = Route.useNavigate();
+ return (
+ <ProjectsSettings
+ projectKey={project ?? null}
+ machineId={machine ?? null}
+ onScopeChange={(project, machine) => {
+ void navigate({
+ search: { project: project ?? undefined, machine: machine ?? undefined },
+ replace: true,
+ });
+ }}
+ />
+ );
+}
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index 747bc52c07e..c76c18544df 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -1,11 +1,28 @@
# Project settings
-Open **Settings → Projects** and select a project to change its preferences.
+Open **Settings → Projects**. The project and machine pickers start at **All projects** and
+**All machines**.
+
+Change the default model, workspace, automatic pull, agent browser access, or actions for projects that inherit those values.
+Select an individual project to override a default. Reset its row to inherit again. Changing a
+default preserves explicit project overrides. Workspace preferences in `t3.json` take precedence
+over machine defaults when the project has no explicit workspace override.
+
+Select a machine to limit edits to it. **All machines** writes defaults to connected machines;
+offline machines keep their previous values. Mixed values are indicated when selected machines
+or checkouts disagree. Browser access changes apply when an agent session next starts.
+
+Project grouping has a client-wide default across machines, with individual checkout overrides.
+Shared actions apply to inheriting projects; editing a project's actions creates an independent list.
+Reset that list to use shared actions again. Existing project actions are preserved.
+
+Project names, icons, removal, and importing actions from a checkout remain project-specific.
+When there are several checkouts, the checkout picker selects which actions and grouping to edit.
## Project icons
Choose an icon, emoji, or image from the project to make it easier to recognize. The choice applies
-to every checkout in the project group and appears on connected clients. Choose **Automatic** to
+to selected checkouts in the project group and appears on connected clients. Choose **Automatic** to
let T3 Code detect an icon again.
## Keep the default branch current
diff --git a/packages/client-runtime/src/state/sharedSettings.test.ts b/packages/client-runtime/src/state/sharedSettings.test.ts
index 8cf0e3bc7f0..712138aab4c 100644
--- a/packages/client-runtime/src/state/sharedSettings.test.ts
+++ b/packages/client-runtime/src/state/sharedSettings.test.ts
@@ -44,13 +44,19 @@ describe("splitSharedServerPatch", () => {
sidebarAutoSettleOnMerge: false,
continueThreadsAfterServerUpdate: true,
enableAgentBrowserAccess: false,
+ defaultThreadEnvMode: "worktree",
+ newWorktreesStartFromOrigin: true,
});
expect(sharedPatch).toEqual({
sidebarAutoSettleAfterDays: 7,
sidebarAutoSettleOnMerge: false,
continueThreadsAfterServerUpdate: true,
+ newWorktreesStartFromOrigin: true,
+ });
+ expect(localPatch).toEqual({
+ enableAgentBrowserAccess: false,
+ defaultThreadEnvMode: "worktree",
});
- expect(localPatch).toEqual({ enableAgentBrowserAccess: false });
});
});
@@ -60,7 +66,6 @@ describe("pickSharedServerSettings", () => {
Object.keys(pickSharedServerSettings(DEFAULT_SERVER_SETTINGS, restartCapabilities)).sort(),
).toEqual([
"continueThreadsAfterServerUpdate",
- "defaultThreadEnvMode",
"newWorktreesStartFromOrigin",
"sidebarAutoSettleAfterDays",
"sidebarAutoSettleOnMerge",
@@ -206,7 +211,12 @@ describe("findSharedSettingsMismatches", () => {
environmentId: boxId,
label: "Remote Box",
syncEligible: true,
- settings: { ...primarySettings, enableAgentBrowserAccess: false },
+ settings: {
+ ...primarySettings,
+ enableAgentBrowserAccess: false,
+ defaultThreadEnvMode:
+ primarySettings.defaultThreadEnvMode === "local" ? "worktree" : "local",
+ },
},
],
});
diff --git a/packages/client-runtime/src/state/sharedSettings.ts b/packages/client-runtime/src/state/sharedSettings.ts
index 128d5c25464..0fd691a64bc 100644
--- a/packages/client-runtime/src/state/sharedSettings.ts
+++ b/packages/client-runtime/src/state/sharedSettings.ts
@@ -24,7 +24,6 @@ const SHARED_SERVER_SETTING_KEYS = [
"continueThreadsAfterServerUpdate",
"sidebarAutoSettleAfterDays",
"sidebarAutoSettleOnMerge",
- "defaultThreadEnvMode",
"newWorktreesStartFromOrigin",
"sourceControlWritingStyle",
] as const satisfies ReadonlyArray<keyof ServerSettings & keyof ServerSettingsPatch>;
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index ce908247737..983e17b5437 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -2,7 +2,12 @@ import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
-import { ForwardCompatibleNullable, TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
+import {
+ ForwardCompatibleNullable,
+ ProjectId,
+ TrimmedNonEmptyString,
+ TrimmedString,
+} from "./baseSchemas.ts";
import { UsageLimitSourceId } from "./usageLimitSourceId.ts";
import { EnvironmentMachineKind, ThreadEnvMode } from "./environment.ts";
import {
@@ -11,7 +16,7 @@ import {
DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
ProviderOptionSelections,
} from "./model.ts";
-import { ModelSelection } from "./orchestration.ts";
+import { ModelSelection, ProjectScript } from "./orchestration.ts";
import { BrowserProfile, BrowserProfileId, DEFAULT_BROWSER_PROFILE_ID } from "./browserProfile.ts";
import {
DEFAULT_PREVIEW_APPEARANCE,
@@ -856,6 +861,22 @@ export const ServerSettings = Schema.Struct({
* between a desktop window and a phone attached to the same server.
*/
enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ projectAgentBrowserAccessOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
+ Schema.withDecodingDefault(Effect.succeed({})),
+ ),
+ defaultAutoPull: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
+ defaultProjectScripts: Schema.Array(ProjectScript).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
+ projectScriptOverrides: Schema.Record(ProjectId, Schema.NullOr(Schema.Array(ProjectScript))).pipe(
+ Schema.withDecodingDefault(Effect.succeed({})),
+ ),
+ projectAutoPullOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
+ Schema.withDecodingDefault(Effect.succeed({})),
+ ),
+ defaultModelSelection: Schema.NullOr(ModelSelection).pipe(
+ Schema.withDecodingDefault(Effect.succeed(null)),
+ ),
sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
),
@@ -1116,6 +1137,18 @@ export const ServerSettingsPatch = Schema.Struct({
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
+ projectAgentBrowserAccessOverrides: Schema.optionalKey(
+ Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
+ ),
+ defaultAutoPull: Schema.optionalKey(Schema.Boolean),
+ defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)),
+ projectScriptOverrides: Schema.optionalKey(
+ Schema.Record(ProjectId, Schema.NullOr(Schema.Array(ProjectScript))),
+ ),
+ projectAutoPullOverrides: Schema.optionalKey(
+ Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
+ ),
+ defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
backgroundActivity: Schema.optionalKey(
diff --git a/packages/shared/src/projectScripts.ts b/packages/shared/src/projectScripts.ts
index 199a55bf3cb..4d98e36b4d7 100644
--- a/packages/shared/src/projectScripts.ts
+++ b/packages/shared/src/projectScripts.ts
@@ -1,4 +1,24 @@
-import type { ProjectScript } from "@t3tools/contracts";
+import type { ProjectId, ProjectScript, ServerSettings } from "@t3tools/contracts";
+
+/** Missing entries preserve existing actions; null explicitly resets a checkout to machine defaults. */
+export function resolveProjectScripts(
+ settings: Pick<ServerSettings, "defaultProjectScripts" | "projectScriptOverrides">,
+ project: { id: ProjectId; scripts: readonly ProjectScript[] },
+): readonly ProjectScript[] {
+ const override = settings.projectScriptOverrides[project.id];
+ if (override === null) return settings.defaultProjectScripts;
+ return (
+ override ?? (project.scripts.length > 0 ? project.scripts : settings.defaultProjectScripts)
+ );
+}
+
+export function projectScriptsInheritDefaults(
+ settings: Pick<ServerSettings, "projectScriptOverrides">,
+ project: { id: ProjectId; scripts: readonly ProjectScript[] },
+): boolean {
+ const override = settings.projectScriptOverrides[project.id];
+ return override === null || (override === undefined && project.scripts.length === 0);
+}
interface ProjectScriptRuntimeEnvInput {
project: {
diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts
index 31f056c211e..a5e428fcdaa 100644
--- a/packages/shared/src/serverSettings.test.ts
+++ b/packages/shared/src/serverSettings.test.ts
@@ -1,5 +1,6 @@
import {
DEFAULT_SERVER_SETTINGS,
+ ProjectId,
ProviderDriverKind,
ProviderInstanceId,
UsageLimitSourceId,
@@ -9,14 +10,181 @@ import * as Duration from "effect/Duration";
import { describe, expect, it } from "vite-plus/test";
import { resolveServerBackgroundActivitySettings } from "./backgroundActivitySettings.ts";
import { createModelSelection } from "./model.ts";
+import { resolveProjectScripts, projectScriptsInheritDefaults } from "./projectScripts.ts";
import {
applyServerSettingsPatch,
isModelSelectionProviderEnabled,
parsePersistedServerObservabilitySettings,
resolveSourceControlWriterModelSelection,
+ resolveProjectAgentBrowserAccess,
+ resolveProjectAutoPull,
} from "./serverSettings.ts";
describe("serverSettings helpers", () => {
+ it("inherits actions, preserves existing actions, and supports empty overrides and reset", () => {
+ const project = { id: ProjectId.make("project-actions"), scripts: [] };
+ const action = {
+ id: "check",
+ name: "Check",
+ command: "npm test",
+ icon: "play" as const,
+ runOnWorktreeCreate: false,
+ };
+ const defaults = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
+ defaultProjectScripts: [action],
+ });
+ expect(resolveProjectScripts(defaults, project)).toEqual([action]);
+ expect(projectScriptsInheritDefaults(defaults, project)).toBe(true);
+ const existing = { ...project, scripts: [{ ...action, command: "npm run lint" }] };
+ expect(resolveProjectScripts(defaults, existing)).toEqual(existing.scripts);
+ expect(projectScriptsInheritDefaults(defaults, existing)).toBe(false);
+ const disabled = applyServerSettingsPatch(defaults, {
+ projectScriptOverrides: { [project.id]: [] },
+ });
+ expect(resolveProjectScripts(disabled, project)).toEqual([]);
+ expect(projectScriptsInheritDefaults(disabled, project)).toBe(false);
+ const changedDefault = applyServerSettingsPatch(disabled, {
+ defaultProjectScripts: [{ ...action, command: "npm run build" }],
+ });
+ expect(resolveProjectScripts(changedDefault, project)).toEqual([]);
+ const reset = applyServerSettingsPatch(changedDefault, {
+ projectScriptOverrides: { [project.id]: null },
+ });
+ expect(resolveProjectScripts(reset, existing)).toEqual(changedDefault.defaultProjectScripts);
+ expect(projectScriptsInheritDefaults(reset, existing)).toBe(true);
+ expect(
+ resolveProjectScripts(
+ applyServerSettingsPatch(reset, { defaultProjectScripts: [] }),
+ existing,
+ ),
+ ).toEqual([]);
+ });
+
+ it("preserves other projects' actions when overriding, clearing, or resetting one project", () => {
+ const firstProject = { id: ProjectId.make("first-project"), scripts: [] };
+ const secondProject = { id: ProjectId.make("second-project"), scripts: [] };
+ const defaultAction = {
+ id: "check",
+ name: "Check",
+ command: "npm test",
+ icon: "play" as const,
+ runOnWorktreeCreate: false,
+ };
+ const firstAction = { ...defaultAction, command: "npm run lint" };
+ const secondAction = { ...defaultAction, command: "npm run build" };
+ const firstUpdate = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
+ defaultProjectScripts: [defaultAction],
+ projectScriptOverrides: { [firstProject.id]: [firstAction] },
+ });
+ const secondUpdate = applyServerSettingsPatch(firstUpdate, {
+ projectScriptOverrides: { [secondProject.id]: [secondAction] },
+ });
+ expect(resolveProjectScripts(secondUpdate, firstProject)).toEqual([firstAction]);
+ expect(resolveProjectScripts(secondUpdate, secondProject)).toEqual([secondAction]);
+
+ const cleared = applyServerSettingsPatch(secondUpdate, {
+ projectScriptOverrides: { [firstProject.id]: [] },
+ });
+ expect(resolveProjectScripts(cleared, firstProject)).toEqual([]);
+ expect(resolveProjectScripts(cleared, secondProject)).toEqual([secondAction]);
+
+ const reset = applyServerSettingsPatch(cleared, {
+ projectScriptOverrides: { [firstProject.id]: null },
+ });
+ expect(resolveProjectScripts(reset, { ...firstProject, scripts: [firstAction] })).toEqual([
+ defaultAction,
+ ]);
+ expect(resolveProjectScripts(reset, secondProject)).toEqual([secondAction]);
+ expect(resolveProjectScripts(secondUpdate, firstProject)).toEqual([firstAction]);
+ });
+
+ it("inherits automatic pull while preserving legacy opt-ins and explicit overrides", () => {
+ const projectId = ProjectId.make("project-pull");
+ expect(resolveProjectAutoPull(DEFAULT_SERVER_SETTINGS, projectId, false)).toBe(false);
+ expect(resolveProjectAutoPull(DEFAULT_SERVER_SETTINGS, projectId, true)).toBe(true);
+ const enabled = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { defaultAutoPull: true });
+ expect(resolveProjectAutoPull(enabled, projectId, false)).toBe(true);
+ const overridden = applyServerSettingsPatch(enabled, {
+ projectAutoPullOverrides: { [projectId]: false },
+ });
+ expect(resolveProjectAutoPull(overridden, projectId, true)).toBe(false);
+ const reset = applyServerSettingsPatch(overridden, {
+ projectAutoPullOverrides: { [projectId]: null },
+ });
+ expect(resolveProjectAutoPull(reset, projectId, false)).toBe(true);
+ const disabled = applyServerSettingsPatch(reset, {
+ defaultAutoPull: false,
+ projectAutoPullOverrides: { [projectId]: true },
+ });
+ expect(resolveProjectAutoPull(disabled, projectId, false)).toBe(true);
+ expect(resolveProjectAutoPull(disabled, ProjectId.make("other-project"), false)).toBe(false);
+ });
+
+ it("inherits browser access and restores inheritance when a project override is removed", () => {
+ const projectId = ProjectId.make("project-browser");
+ const otherProjectId = ProjectId.make("other-project");
+ const overridden = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
+ projectAgentBrowserAccessOverrides: { [projectId]: false },
+ });
+ expect(resolveProjectAgentBrowserAccess(overridden, projectId)).toBe(false);
+ expect(resolveProjectAgentBrowserAccess(overridden, otherProjectId)).toBe(true);
+ const reset = applyServerSettingsPatch(overridden, {
+ projectAgentBrowserAccessOverrides: { [projectId]: null },
+ });
+ expect(resolveProjectAgentBrowserAccess(reset, projectId)).toBe(true);
+ const enabled = applyServerSettingsPatch(reset, {
+ enableAgentBrowserAccess: false,
+ projectAgentBrowserAccessOverrides: { [projectId]: true },
+ });
+ expect(resolveProjectAgentBrowserAccess(enabled, projectId)).toBe(true);
+ expect(resolveProjectAgentBrowserAccess(enabled, otherProjectId)).toBe(false);
+ });
+
+ it("preserves other projects' boolean overrides across separate updates and resets", () => {
+ const firstProjectId = ProjectId.make("first-project");
+ const secondProjectId = ProjectId.make("second-project");
+ const firstUpdate = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
+ defaultAutoPull: true,
+ projectAutoPullOverrides: { [firstProjectId]: false },
+ projectAgentBrowserAccessOverrides: { [firstProjectId]: false },
+ });
+ const secondUpdate = applyServerSettingsPatch(firstUpdate, {
+ projectAutoPullOverrides: { [secondProjectId]: false },
+ projectAgentBrowserAccessOverrides: { [secondProjectId]: false },
+ });
+ for (const projectId of [firstProjectId, secondProjectId]) {
+ expect(resolveProjectAutoPull(secondUpdate, projectId, false)).toBe(false);
+ expect(resolveProjectAgentBrowserAccess(secondUpdate, projectId)).toBe(false);
+ }
+
+ const reset = applyServerSettingsPatch(secondUpdate, {
+ projectAutoPullOverrides: { [firstProjectId]: null },
+ projectAgentBrowserAccessOverrides: { [firstProjectId]: null },
+ });
+ expect(resolveProjectAutoPull(reset, firstProjectId, false)).toBe(true);
+ expect(resolveProjectAgentBrowserAccess(reset, firstProjectId)).toBe(true);
+ expect(resolveProjectAutoPull(reset, secondProjectId, false)).toBe(false);
+ expect(resolveProjectAgentBrowserAccess(reset, secondProjectId)).toBe(false);
+ expect(reset.projectAutoPullOverrides[firstProjectId]).toBeUndefined();
+ expect(reset.projectAgentBrowserAccessOverrides[firstProjectId]).toBeUndefined();
+ expect(resolveProjectAutoPull(secondUpdate, firstProjectId, false)).toBe(false);
+ expect(resolveProjectAgentBrowserAccess(secondUpdate, firstProjectId)).toBe(false);
+ });
+
+ it("replaces and clears conversation model defaults without retaining old options", () => {
+ const current = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
+ defaultModelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
+ { id: "reasoningEffort", value: "high" },
+ ]),
+ });
+ const selection = createModelSelection(ProviderInstanceId.make("claudeAgent"), "sonnet");
+ const updated = applyServerSettingsPatch(current, { defaultModelSelection: selection });
+ expect(updated.defaultModelSelection).toEqual(selection);
+ expect(
+ applyServerSettingsPatch(updated, { defaultModelSelection: null }).defaultModelSelection,
+ ).toBeNull();
+ });
+
it("ignores missing and blank persisted observability URLs", () => {
expect(parsePersistedServerObservabilitySettings("{}")).toEqual({
otlpTracesUrl: undefined,
diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts
index dc50da2d762..f969e4412c3 100644
--- a/packages/shared/src/serverSettings.ts
+++ b/packages/shared/src/serverSettings.ts
@@ -3,6 +3,7 @@ import {
isProviderAvailable,
resolveProviderInstanceEnabled,
type ModelSelection,
+ type ProjectId,
type ProviderDriverKind,
type ServerProvider,
ServerSettings,
@@ -23,6 +24,27 @@ import {
const ServerSettingsJson = fromLenientJson(ServerSettings);
const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
+export function resolveProjectAgentBrowserAccess(
+ settings: Pick<ServerSettings, "enableAgentBrowserAccess" | "projectAgentBrowserAccessOverrides">,
+ projectId: ProjectId,
+): boolean {
+ return (
+ settings.projectAgentBrowserAccessOverrides[projectId] ?? settings.enableAgentBrowserAccess
+ );
+}
+
+export function resolveProjectAutoPull(
+ settings: Pick<ServerSettings, "defaultAutoPull" | "projectAutoPullOverrides">,
+ projectId: ProjectId,
+ legacyAutoPull: boolean | undefined,
+): boolean {
+ // Existing opt-ins stay enabled until explicitly overridden or reset.
+ return (
+ settings.projectAutoPullOverrides[projectId] ??
+ (legacyAutoPull === true || settings.defaultAutoPull)
+ );
+}
+
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
const getLegacyProviderSettings = (
@@ -151,6 +173,8 @@ export function applyServerSettingsPatch(
// Merged per entry below; its `null` removals must not reach deepMerge.
usageLimitSources: usageLimitSourcesPatch,
usagePriceOverrides: usagePriceOverridesPatch,
+ projectAgentBrowserAccessOverrides: projectAgentBrowserAccessOverridesPatch,
+ projectAutoPullOverrides: projectAutoPullOverridesPatch,
...patchForMerge
} = patch;
const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
@@ -207,6 +231,36 @@ export function applyServerSettingsPatch(
...(patch.providerInstances !== undefined
? { providerInstances: patch.providerInstances }
: {}),
+ ...(projectAgentBrowserAccessOverridesPatch !== undefined
+ ? {
+ projectAgentBrowserAccessOverrides: mergeSettingsEntries(
+ current.projectAgentBrowserAccessOverrides,
+ projectAgentBrowserAccessOverridesPatch,
+ ),
+ }
+ : {}),
+ ...(projectAutoPullOverridesPatch !== undefined
+ ? {
+ projectAutoPullOverrides: mergeSettingsEntries(
+ current.projectAutoPullOverrides,
+ projectAutoPullOverridesPatch,
+ ),
+ }
+ : {}),
+ ...(patch.defaultModelSelection !== undefined
+ ? { defaultModelSelection: patch.defaultModelSelection }
+ : {}),
+ ...(patch.defaultProjectScripts !== undefined
+ ? { defaultProjectScripts: patch.defaultProjectScripts }
+ : {}),
+ ...(patch.projectScriptOverrides !== undefined
+ ? {
+ projectScriptOverrides: {
+ ...current.projectScriptOverrides,
+ ...patch.projectScriptOverrides,
+ },
+ }
+ : {}),
...(usageLimitSourcesPatch !== undefined
? {
usageLimitSources: mergeSettingsEntries(