feat(projects): automatically pull clean default branches (#9277)

Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
mariaandmaria-rcks authored and GitHub committed 2026-09-02 18:29:07 -04:00
1 parent 91c8d4771c
commit ba3cb07738
20 files changed
+351 -2

No files matched your search

@@ -40,6 +40,7 @@ import * as ServerLifecycleEvents from "../src/serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "../src/serverRuntimeStartup.ts";
import * as ServerSettings from "../src/serverSettings.ts";
import * as AnalyticsService from "../src/telemetry/AnalyticsService.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
const providerInstanceId = ProviderInstanceId.make("codex");
const projectId = ProjectId.make("project-startup-orphan");
@@ -105,6 +106,7 @@ const startupDependencies = Layer.mergeAll(
}),
),
AnalyticsService.layerTest,
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
Layer.succeed(ProviderService.ProviderService, {
startSession: () => Effect.die("unused"),
sendTurn: () => Effect.die("unused"),
@@ -515,6 +515,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
workspaceRoot: event.payload.workspaceRoot,
defaultModelSelection: event.payload.defaultModelSelection,
defaultThreadEnvMode: null,
autoPull: false,
faviconPath: event.payload.faviconPath ?? null,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
@@ -542,6 +543,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: event.payload.defaultThreadEnvMode }
: {}),
...(event.payload.autoPull !== undefined ? { autoPull: event.payload.autoPull } : {}),
...(event.payload.faviconPath !== undefined
? { faviconPath: event.payload.faviconPath }
: {}),
@@ -278,6 +278,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
autoPull: false,
faviconPath: null,
scripts: [
{
@@ -405,6 +406,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
autoPull: false,
faviconPath: null,
scripts: [
{
@@ -83,6 +83,7 @@ const THREAD_DETAIL_ACTIVITY_PAYLOAD_BATCH_SIZE = 25;
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
autoPull: Schema.Number,
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
);
@@ -347,6 +348,7 @@ function mapProjectShellRow(
repositoryIdentity,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
autoPull: row.autoPull === 1,
faviconPath: row.faviconPath ?? null,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -439,6 +441,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
auto_pull AS "autoPull",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -914,6 +917,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
auto_pull AS "autoPull",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -938,6 +942,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
auto_pull AS "autoPull",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -1878,6 +1883,7 @@ pending_approval_requests AS (
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
autoPull: row.autoPull === 1,
faviconPath: row.faviconPath ?? null,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -2013,6 +2019,7 @@ pending_approval_requests AS (
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
autoPull: row.autoPull === 1,
faviconPath: row.faviconPath ?? null,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -2534,6 +2541,7 @@ pending_approval_requests AS (
repositoryIdentity,
defaultModelSelection: option.value.defaultModelSelection,
defaultThreadEnvMode: option.value.defaultThreadEnvMode,
autoPull: option.value.autoPull === 1,
faviconPath: option.value.faviconPath ?? null,
scripts: option.value.scripts,
createdAt: option.value.createdAt,
@@ -153,4 +153,26 @@ it.layer(NodeServices.layer)("decider project defaults", (it) => {
expect(afterClear.projects[0]?.defaultThreadEnvMode).toBeNull();
}),
);
it.effect("propagates autoPull through meta.update into the read model", () =>
Effect.gen(function* () {
const readModel = yield* projectEvent(createEmptyReadModel(now), seedProjectCreated(1));
expect(readModel.projects[0]?.autoPull).toBe(false);
const result = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-auto-pull"),
projectId,
autoPull: true,
},
readModel,
});
const event = Array.isArray(result) ? result[0] : result;
expect((event.payload as { autoPull?: unknown }).autoPull).toBe(true);
const updated = yield* projectEvent(readModel, { ...event, sequence: 2 });
expect(updated.projects[0]?.autoPull).toBe(true);
}),
);
});
+1
View File
@@ -264,6 +264,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: command.defaultThreadEnvMode }
: {}),
...(command.autoPull !== undefined ? { autoPull: command.autoPull } : {}),
...(command.faviconPath !== undefined ? { faviconPath: command.faviconPath } : {}),
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
updatedAt: occurredAt,
@@ -215,6 +215,7 @@ export function projectEvent(
workspaceRoot: payload.workspaceRoot,
defaultModelSelection: payload.defaultModelSelection,
defaultThreadEnvMode: null,
autoPull: false,
faviconPath: payload.faviconPath ?? null,
scripts: payload.scripts,
createdAt: payload.createdAt,
@@ -251,6 +252,7 @@ export function projectEvent(
...(payload.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: payload.defaultThreadEnvMode }
: {}),
...(payload.autoPull !== undefined ? { autoPull: payload.autoPull } : {}),
...(payload.faviconPath !== undefined
? { faviconPath: payload.faviconPath }
: {}),
@@ -2,6 +2,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
@@ -18,6 +19,7 @@ import {
const ProjectionProjectDbRow = ProjectionProject.mapFields(
Struct.assign({
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
autoPull: Schema.Number,
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
);
@@ -36,6 +38,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root,
default_model_selection_json,
default_thread_env_mode,
auto_pull,
favicon_path,
scripts_json,
created_at,
@@ -48,6 +51,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.workspaceRoot},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${row.defaultThreadEnvMode},
${row.autoPull ? 1 : 0},
${row.faviconPath ?? null},
${JSON.stringify(row.scripts)},
${row.createdAt},
@@ -60,6 +64,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root = excluded.workspace_root,
default_model_selection_json = excluded.default_model_selection_json,
default_thread_env_mode = excluded.default_thread_env_mode,
auto_pull = excluded.auto_pull,
favicon_path = excluded.favicon_path,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
@@ -79,6 +84,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
auto_pull AS "autoPull",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -100,6 +106,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
auto_pull AS "autoPull",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -126,11 +133,13 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
getProjectionProjectRow(input).pipe(
Effect.map(Option.map((row) => ({ ...row, autoPull: row.autoPull === 1 }))),
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
);
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
listProjectionProjectRows().pipe(
Effect.map((rows) => rows.map((row) => ({ ...row, autoPull: row.autoPull === 1 }))),
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
);
@@ -34,6 +34,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
model: "gpt-5.4",
},
defaultThreadEnvMode: null,
autoPull: false,
scripts: [],
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
@@ -56,6 +56,7 @@ import Migration0041 from "./Migrations/041_AuthSessionClientConnection.ts";
import Migration0042 from "./Migrations/042_ProjectionThreadLinkedPullRequest.ts";
import Migration0043 from "./Migrations/043_ProjectionThreadsUnsettledAt.ts";
import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.ts";
import Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";
/**
* Migration loader with all migrations defined inline.
@@ -112,6 +113,7 @@ export const migrationEntries = [
[42, "ProjectionThreadLinkedPullRequest", Migration0042],
[43, "ProjectionThreadsUnsettledAt", Migration0043],
[44, "ClearAutomaticProjectModelDefaults", Migration0044],
[45, "ProjectionProjectsAutoPull", Migration0045],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_projects)
`;
if (!columns.some((column) => column.name === "auto_pull")) {
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN auto_pull INTEGER NOT NULL DEFAULT 0
`;
}
});
@@ -26,6 +26,7 @@ export const ProjectionProject = Schema.Struct({
workspaceRoot: Schema.String,
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultThreadEnvMode: Schema.NullOr(ThreadEnvMode),
autoPull: Schema.Boolean,
faviconPath: Schema.optional(Schema.NullOr(Schema.String)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
+6 -1
View File
@@ -339,7 +339,12 @@ const VcsLayerLive = Layer.empty.pipe(
Layer.provideMerge(GitWorkflowLayerLive),
Layer.provideMerge(ReviewLayerLive),
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
Layer.provideMerge(
VcsStatusBroadcaster.layer.pipe(
Layer.provide(GitWorkflowLayerLive),
Layer.provide(VcsStatusBroadcaster.autoPullPolicyLayer),
),
),
);
const CheckpointingLayerLive = Layer.empty.pipe(
@@ -15,6 +15,7 @@ import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngi
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
it("uses the canonical Codex default for the auto-bootstrapped welcome thread", () => {
assert.deepStrictEqual(ServerRuntimeStartup.getAutoBootstrapThreadModelSelection(), {
@@ -23,6 +24,45 @@ it("uses the canonical Codex default for the auto-bootstrapped welcome thread",
});
});
it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () =>
Effect.gen(function* () {
const pulled: string[] = [];
const git = {
statusDetails: (cwd: string) =>
Effect.succeed({
isRepo: true,
isDefaultBranch: cwd !== "/feature",
hasUpstream: true,
hasWorkingTreeChanges: cwd === "/dirty",
aheadCount: cwd === "/ahead" ? 1 : 0,
behindCount: cwd === "/current" ? 0 : 1,
} as never),
pullCurrentBranch: (cwd: string) =>
Effect.sync(() => {
pulled.push(cwd);
return {
status: "pulled" as const,
refName: "main",
upstreamRef: "origin/main",
};
}),
} as unknown as GitVcsDriver.GitVcsDriver["Service"];
const project = (workspaceRoot: string, autoPull = true) =>
({ workspaceRoot, autoPull }) as never;
yield* ServerRuntimeStartup.autoPullProjects([
project("/clean"),
project("/current"),
project("/dirty"),
project("/ahead"),
project("/feature"),
project("/disabled", false),
]).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git));
assert.deepStrictEqual(pulled, ["/clean"]);
}),
);
it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
Effect.scoped(
Effect.gen(function* () {
+71
View File
@@ -3,6 +3,7 @@ import {
DEFAULT_MODEL,
DEFAULT_PROVIDER_INTERACTION_MODE,
type ModelSelection,
type OrchestrationProjectShell,
ProjectId,
ProviderInstanceId,
ThreadId,
@@ -40,6 +41,7 @@ import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDi
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
import { forkParked } from "./serverActivation.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import {
formatHeadlessServeOutput,
formatHostForUrl,
@@ -634,6 +636,65 @@ interface StartupOptions {
readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
}
export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
projects: ReadonlyArray<OrchestrationProjectShell>,
) {
const git = yield* GitVcsDriver.GitVcsDriver;
const workspaceRoots = [
...new Set(
projects
.filter((project) => project.autoPull === true)
.map((project) => project.workspaceRoot),
),
];
yield* Effect.forEach(
workspaceRoots,
(cwd) =>
Effect.gen(function* () {
const status = yield* git.statusDetails(cwd);
if (
!status.isRepo ||
!status.isDefaultBranch ||
!status.hasUpstream ||
status.hasWorkingTreeChanges ||
status.aheadCount > 0
) {
yield* Effect.logDebug("Skipped automatic project pull", {
cwd,
reason: !status.isRepo
? "not-a-repository"
: !status.isDefaultBranch
? "not-on-default-branch"
: !status.hasUpstream
? "no-upstream"
: status.hasWorkingTreeChanges
? "working-tree-changes"
: "local-commits",
});
return;
}
if (status.behindCount <= 0) return;
const result = yield* git.pullCurrentBranch(cwd);
yield* Effect.logDebug("Automatic project pull completed", {
cwd,
status: result.status,
refName: result.refName,
});
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("Automatic project pull failed", {
cwd,
cause,
}),
),
),
{ concurrency: 4, discard: true },
);
});
export const make = (options?: StartupOptions) =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
@@ -652,6 +713,13 @@ export const make = (options?: StartupOptions) =>
const httpListening = yield* Deferred.make<void>();
const reactorScope = yield* Scope.make("sequential");
const syncAutoPullProjects = projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.flatMap((snapshot) => autoPullProjects(snapshot.projects)),
Effect.catch((cause) =>
Effect.logWarning("Failed to load projects for automatic pull", { cause }),
),
);
yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
const startup = Effect.gen(function* () {
@@ -696,6 +764,9 @@ export const make = (options?: StartupOptions) =>
yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
yield* Effect.logDebug("startup phase: syncing clean projects");
yield* runStartupPhase("projects.auto-pull", syncAutoPullProjects);
const welcomeBase = yield* resolveWelcomeBase;
const environment = yield* serverEnvironment.getDescriptor;
yield* Effect.logDebug("startup phase: preparing welcome payload");
@@ -142,6 +142,67 @@ function makeBackgroundPolicyLayer(shouldRunScopeWork: (scope: BackgroundScope)
}
describe("VcsStatusBroadcaster", () => {
it.effect(
"automatically pulls an enabled clean default branch when status detects it is behind",
() => {
let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
let pullCalls = 0;
let configuredWorkspaceRoot = "";
const localStatus: VcsStatusLocalResult = {
...baseLocalStatus,
isDefaultRef: true,
refName: "main",
};
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => true)),
Layer.provide(
Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
}),
),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(localStatus),
remoteStatus: () => Effect.succeed(remoteStatus),
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
invalidateStatus: () => Effect.void,
pullCurrentBranch: () =>
Effect.sync(() => {
pullCalls += 1;
remoteStatus = { ...remoteStatus, behindCount: 0 };
return {
status: "pulled" as const,
refName: "main",
upstreamRef: "origin/main",
};
}),
}),
),
);
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const realDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-auto-pull-real-",
});
const linkParent = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-auto-pull-link-",
});
configuredWorkspaceRoot = path.join(linkParent, "repo-link");
yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
assert.equal(pullCalls, 1);
assert.equal(status.behindCount, 0);
}).pipe(Effect.provide(testLayer));
},
);
it.effect("reuses the cached VCS status across repeated reads", () => {
const state = {
currentLocalStatus: baseLocalStatus,
+69 -1
View File
@@ -24,6 +24,7 @@ import { mergeGitStatusParts } from "@t3tools/shared/git";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
@@ -139,6 +140,26 @@ interface StreamStatusOptions {
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
}
export class VcsAutoPullPolicy extends Context.Reference<{
readonly isEnabled: (cwd: string) => Effect.Effect<boolean, never>;
}>("t3/vcs/VcsAutoPullPolicy", {
defaultValue: () => ({ isEnabled: () => Effect.succeed(false) }),
}) {}
export const autoPullPolicyLayer = Layer.effect(
VcsAutoPullPolicy,
Effect.gen(function* () {
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
return {
isEnabled: (cwd: string) =>
snapshots.getActiveProjectByWorkspaceRoot(cwd).pipe(
Effect.map((project) => project._tag === "Some" && project.value.autoPull === true),
Effect.orElseSucceed(() => false),
),
};
}),
);
export function remoteRefreshFailureDelay(
consecutiveFailures: number,
configuredInterval: Duration.Duration,
@@ -181,6 +202,7 @@ const normalizeCwd = (cwd: string) =>
);
export const make = Effect.gen(function* () {
const autoPullPolicy = yield* VcsAutoPullPolicy;
const workflow = yield* GitWorkflowService.GitWorkflowService;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const fs = yield* FileSystem.FileSystem;
@@ -354,14 +376,57 @@ export const make = Effect.gen(function* () {
return yield* refreshLocalStatusCore(cwd);
});
const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
cwd: string,
remote: VcsStatusRemoteResult | null,
policyCwds: ReadonlyArray<string>,
) {
return yield* Effect.gen(function* () {
const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
concurrency: "unbounded",
})).some(Boolean);
if (
remote === null ||
!remote.hasUpstream ||
remote.aheadCount > 0 ||
remote.behindCount <= 0 ||
!autoPullEnabled
) {
return null;
}
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;
yield* workflow.pullCurrentBranch(cwd);
yield* workflow.invalidateStatus(cwd);
const [refreshedLocal, refreshedRemote] = yield* Effect.all(
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],
{ concurrency: "unbounded" },
);
yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });
return { local: refreshedLocal, remote: refreshedRemote };
}).pipe(
Effect.catch(() =>
Effect.logWarning("Automatic project pull failed", { cwd }).pipe(Effect.as(null)),
),
);
});
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
cwd: string,
options?: { readonly refreshUpstream?: boolean },
options?: {
readonly refreshUpstream?: boolean;
readonly policyCwds?: ReadonlyArray<string>;
},
) {
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus({ cwd }, options);
const pulled = yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
if (pulled !== null) return pulled.remote;
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
@@ -376,6 +441,8 @@ export const make = Effect.gen(function* () {
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
{ concurrency: "unbounded" },
);
const pulled = yield* maybeAutoPull(cwd, remote, [rawCwd]);
if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
});
@@ -416,6 +483,7 @@ export const make = Effect.gen(function* () {
const exit = yield* refreshRemoteStatus(cwd, {
refreshUpstream: !Duration.isZero(configuredInterval),
policyCwds: [...demandCwds.keys()],
}).pipe(Effect.exit);
if (Exit.isSuccess(exit)) {
yield* Ref.set(needsInitialRefreshRef, false);
@@ -96,6 +96,7 @@ import {
} 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 {
@@ -371,6 +372,7 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
title: string;
defaultModelSelection: ModelSelection | null;
defaultThreadEnvMode: ThreadEnvMode | null;
autoPull: boolean;
faviconPath: string | null;
}>,
failureTitle: string,
@@ -464,6 +466,13 @@ 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],
);
// ----- favicon -----
const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);
const [isSavingFavicon, setIsSavingFavicon] = useState(false);
@@ -940,6 +949,17 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
</Select>
}
/>
<SettingsRow
title="Automatically pull"
description="Keeps the default branch current in the background when the checkout has no local changes or commits."
control={
<Switch
checked={autoPull}
aria-label="Automatically pull the default branch"
onCheckedChange={setAutoPull}
/>
}
/>
</SettingsSection>
<SettingsSection
+10
View File
@@ -14,3 +14,13 @@ T3 Code supports SVG, PNG, ICO, JPEG, GIF, AVIF, and WebP files. The selected pa
each checkout in the project group and appears on your connected clients.
To use automatic detection again, select **Automatic**.
## Keep the default branch current
Turn on **Automatically pull** in a project's settings to keep its default-branch checkout current.
T3 Code checks in the background and when the server starts. It uses the branch's configured
upstream and only performs a fast-forward pull when the checkout has no working-tree changes,
untracked files, or local commits.
The pull is skipped if the checkout is on another branch, has no upstream, or contains local work.
Pull failures do not prevent the server from starting.
+6
View File
@@ -291,6 +291,9 @@ export const OrchestrationProject = Schema.Struct({
// Per-project override for where new threads start. Null/absent means
// "no override": clients fall back to t3.json, then the global setting.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
// Opt-in because background sync performs network I/O and may move the checkout.
// Optional on the wire so cached snapshots from older servers still decode.
autoPull: Schema.optional(Schema.Boolean),
// Optional on the wire so cached snapshots from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.Array(ProjectScript),
@@ -502,6 +505,7 @@ export const OrchestrationProjectShell = Schema.Struct({
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
autoPull: Schema.optional(Schema.Boolean),
// Optional on the wire so cached snapshots from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.Array(ProjectScript),
@@ -723,6 +727,7 @@ const ProjectMetaUpdateCommand = Schema.Struct({
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
// Absent = leave unchanged; null = clear the override.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
autoPull: Schema.optional(Schema.Boolean),
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
});
@@ -1191,6 +1196,7 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
autoPull: Schema.optional(Schema.Boolean),
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
updatedAt: IsoDateTime,