:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): move local task defaults to the server behind a flag (#111224)
Shy Alter584200b163fe
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 4d831c4fc37c..a0d7b44712b2 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -402,10 +402,17 @@ export const NO_TASK_RUN_PREFERENCES: TaskRunPreferences = {reasoning_effort: null,};+/** The signed-in user's defaults for new tasks. Null means never set. */+export interface TaskDefaults {+ start_in_plan_mode: boolean | null;+ auto_publish_cloud_runs: boolean | null;+}+/** What the signed-in user has stored for this project, and what it resolves to. */export interface MyTaskRunConfig {preferences: TaskRunPreferences;resolved: TaskRunDefaults;+ taskDefaults: TaskDefaults;}export interface TaskSessionStorageAccess {@@ -2613,6 +2620,7 @@ export class PostHogAPIClient {const payload = (await response.json()) as {ai_run_preferences?: Partial<TaskRunPreferences> | null;resolved_ai_run_defaults?: TaskRunDefaults | null;+ task_defaults?: Partial<TaskDefaults> | null;};return {// The API stores a cleared preference as `{}`, so read each field rather than@@ -2624,9 +2632,31 @@ export class PostHogAPIClient {reasoning_effort: payload.ai_run_preferences?.reasoning_effort ?? null,},resolved: payload.resolved_ai_run_defaults ?? NO_TASK_RUN_DEFAULTS,+ taskDefaults: {+ start_in_plan_mode: payload.task_defaults?.start_in_plan_mode ?? null,+ auto_publish_cloud_runs:+ payload.task_defaults?.auto_publish_cloud_runs ?? null,+ },};}+ /** Save some of the signed-in user's task defaults. Fields left out keep their value. */+ async setMyTaskDefaults(+ projectId: number,+ changes: Partial<Record<keyof TaskDefaults, boolean>>,+ ): Promise<void> {+ const urlPath = `/api/projects/${projectId}/tasks/@me/config/task_defaults/`;+ const response = await this.api.fetcher.fetch({+ method: "post",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ overrides: { body: JSON.stringify(changes) },+ });+ if (!response.ok) {+ throw new Error(`Task defaults update failed: ${response.status}`);+ }+ }+async listSignalSourceConfigs(projectId: number,): Promise<SignalSourceConfig[]> {diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.jsonindex f366bd7f56b9..02989a896e50 100644--- a/products/desktop/packages/shared/src/feature-flag-keys.json+++ b/products/desktop/packages/shared/src/feature-flag-keys.json@@ -28,6 +28,7 @@"SAVED_SEARCHES_RAIL_FLAG": "posthog-desktop-saved-searches-rail","SELF_DRIVING_SETUP_TASK_FLAG": "posthog-code-self-driving-setup-task","SERVER_AGENT_INSTRUCTIONS_FLAG": "posthog-desktop-server-agent-instructions",+ "SERVER_TASK_DEFAULTS_FLAG": "posthog-desktop-server-task-defaults","SETTINGS_BACKUP_FLAG": "posthog-desktop-settings-backup","SIGNALS_PR_REFUNDS_FLAG": "signals-pr-refunds","SPACE_SETUP_FLAG": "code-space-setup",diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.tsindex 17fedb08edcb..a44b6c293a39 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -101,3 +101,6 @@ export const USER_SPEND_LIMIT_FLAG = featureFlagKeys.USER_SPEND_LIMIT_FLAG;/** Move local custom instructions to "My instructions" on the server, then stop adding them to cloud tasks. */export const SERVER_AGENT_INSTRUCTIONS_FLAG =featureFlagKeys.SERVER_AGENT_INSTRUCTIONS_FLAG;+/** Move local task defaults to the server once, then keep "always create pull requests" in step with it. */+export const SERVER_TASK_DEFAULTS_FLAG =+ featureFlagKeys.SERVER_TASK_DEFAULTS_FLAG;diff --git a/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.contribution.ts b/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.contribution.tsnew file mode 100644index 000000000000..ba5fffb96d86--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.contribution.ts@@ -0,0 +1,130 @@+import type { Contribution } from "@posthog/di/contribution";+import {+ HOST_TRPC_CLIENT,+ type HostTrpcClient,+} from "@posthog/host-router/client";+import { SERVER_TASK_DEFAULTS_FLAG } from "@posthog/shared";+import { createAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStore } from "@posthog/ui/features/auth/store";+import {+ FEATURE_FLAGS,+ type FeatureFlags,+} from "@posthog/ui/features/feature-flags/identifiers";+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";+import { logger } from "@posthog/ui/shell/logger";+import { inject, injectable } from "inversify";+import { nextTaskDefaultsSync } from "./serverTaskDefaults";++const log = logger.scope("server-task-defaults");++/**+ * Keeps the task defaults on the server in step with Desktop for each project+ * the person opens. Desktop still starts tasks from its local settings, so a+ * failed request changes nothing for the person.+ */+@injectable()+export class ServerTaskDefaultsContribution implements Contribution {+ private readonly inFlight = new Set<number>();+ private readonly rerun = new Set<number>();++ constructor(+ @inject(HOST_TRPC_CLIENT)+ private readonly hostClient: HostTrpcClient,+ @inject(FEATURE_FLAGS)+ private readonly flags: FeatureFlags,+ ) {}++ start(): void {+ this.flags.onFlagsLoaded(() => void this.reconcile(true));+ useAuthStore.subscribe((state, prev) => {+ if (+ state.authState.currentProjectId !== prev.authState.currentProjectId ||+ state.authState.status !== prev.authState.status+ ) {+ void this.reconcile(true);+ }+ });+ useSettingsStore.subscribe((state, prev) => {+ if (+ state._hasHydrated !== prev._hasHydrated ||+ state.autoPublishCloudRuns !== prev.autoPublishCloudRuns+ ) {+ void this.reconcile(false);+ }+ });+ void this.reconcile(true);+ }++ // `fetchAlways` reads the server even when Desktop has nothing new, to pick+ // up a change made on web.+ private async reconcile(fetchAlways: boolean): Promise<void> {+ if (!this.flags.isEnabled(SERVER_TASK_DEFAULTS_FLAG)) return;+ const settings = useSettingsStore.getState();+ const authState = useAuthStore.getState().authState;+ const projectId = authState.currentProjectId;+ if (!settings._hasHydrated || projectId == null) return;+ const synced = settings.taskDefaultsOnServer[String(projectId)];+ const local = settings.autoPublishCloudRuns;+ if (+ !fetchAlways &&+ synced?.planModeOffered &&+ synced.autoPublishCloudRuns === local+ ) {+ return;+ }+ if (this.inFlight.has(projectId)) {+ this.rerun.add(projectId);+ return;+ }+ const client = createAuthenticatedClient(+ authState,+ () =>+ this.hostClient.auth.getValidAccessToken+ .query()+ .then((r) => r.accessToken),+ () =>+ this.hostClient.auth.refreshAccessToken+ .mutate()+ .then((r) => r.accessToken),+ );+ if (!client) return;++ this.inFlight.add(projectId);+ try {+ const { taskDefaults } = await client.getMyTaskRunConfig(projectId);+ const sync = nextTaskDefaultsSync({+ server: taskDefaults,+ localAutoPublishCloudRuns: local,+ localInitialTaskMode: settings.defaultInitialTaskMode,+ synced,+ });+ if (Object.keys(sync.upload).length > 0) {+ await client.setMyTaskDefaults(projectId, sync.upload);+ }+ const store = useSettingsStore.getState();+ if (store.autoPublishCloudRuns !== local) {+ // The person changed the setting while the request ran. The rerun+ // sends that change.+ this.rerun.add(projectId);+ store.setTaskDefaultsOnServer(projectId, {+ ...sync.synced,+ autoPublishCloudRuns: local,+ });+ return;+ }+ // Record the sync before the local value changes, so that change does+ // not read as a Desktop edit.+ store.setTaskDefaultsOnServer(projectId, sync.synced);+ if (sync.pullAutoPublishCloudRuns !== null) {+ store.setAutoPublishCloudRuns(sync.pullAutoPublishCloudRuns);+ }+ } catch (err) {+ log.warn("Failed to sync task defaults with the server", err);+ } finally {+ this.inFlight.delete(projectId);+ if (this.rerun.delete(projectId)) {+ void this.reconcile(false);+ }+ }+ }+}diff --git a/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.test.ts b/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.test.tsnew file mode 100644index 000000000000..a73410ee39bc--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from "vitest";+import { nextTaskDefaultsSync } from "./serverTaskDefaults";++const UNSET = { start_in_plan_mode: null, auto_publish_cloud_runs: null };++describe("serverTaskDefaults", () => {+ it.each([+ [+ "nothing set on the server: Desktop values move up",+ UNSET,+ true,+ "plan",+ undefined,+ { start_in_plan_mode: true, auto_publish_cloud_runs: true },+ null,+ true,+ ],+ [+ "'Last used' is not offered to the server",+ UNSET,+ false,+ "last_used",+ undefined,+ { auto_publish_cloud_runs: false },+ null,+ false,+ ],+ [+ "values chosen on web win on the first sync",+ { start_in_plan_mode: false, auto_publish_cloud_runs: false },+ true,+ "plan",+ undefined,+ {},+ false,+ false,+ ],+ [+ "a Desktop change since the last sync moves up",+ { start_in_plan_mode: true, auto_publish_cloud_runs: true },+ false,+ "plan",+ { autoPublishCloudRuns: true, planModeOffered: true },+ { auto_publish_cloud_runs: false },+ null,+ false,+ ],+ [+ "a web change since the last sync comes down",+ { start_in_plan_mode: true, auto_publish_cloud_runs: false },+ true,+ "plan",+ { autoPublishCloudRuns: true, planModeOffered: true },+ {},+ false,+ false,+ ],+ [+ "in step: nothing to do",+ { start_in_plan_mode: null, auto_publish_cloud_runs: true },+ true,+ "plan",+ { autoPublishCloudRuns: true, planModeOffered: true },+ {},+ null,+ true,+ ],+ ] as const)(+ "%s",+ (_case, server, local, mode, synced, upload, pull, agreed) => {+ expect(+ nextTaskDefaultsSync({+ server,+ localAutoPublishCloudRuns: local,+ localInitialTaskMode: mode,+ synced,+ }),+ ).toEqual({+ upload,+ pullAutoPublishCloudRuns: pull,+ synced: { autoPublishCloudRuns: agreed, planModeOffered: true },+ });+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.ts b/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.tsnew file mode 100644index 000000000000..a9623eec2f69--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/serverTaskDefaults.ts@@ -0,0 +1,60 @@+import type { TaskDefaults } from "@posthog/api-client/posthog-client";+import type {+ DefaultInitialTaskMode,+ TaskDefaultsSyncState,+} from "./settingsStore";++export interface TaskDefaultsSync {+ upload: Partial<Record<keyof TaskDefaults, boolean>>;+ // Set when the server holds a newer "always create pull requests" value.+ pullAutoPublishCloudRuns: boolean | null;+ synced: TaskDefaultsSyncState;+}++/**+ * What to sync between Desktop and the task defaults on the server for one+ * project. A value nobody set on the server takes the Desktop value, so Desktop+ * users keep what they have. "Start in" is offered once and stays local after.+ * "Always create pull requests" stays in step both ways: the side that changed+ * since the last sync wins.+ */+export function nextTaskDefaultsSync(input: {+ server: TaskDefaults;+ localAutoPublishCloudRuns: boolean;+ localInitialTaskMode: DefaultInitialTaskMode;+ synced: TaskDefaultsSyncState | undefined;+}): TaskDefaultsSync {+ const { server, localAutoPublishCloudRuns: local, synced } = input;+ const upload: TaskDefaultsSync["upload"] = {};++ if (+ !synced?.planModeOffered &&+ server.start_in_plan_mode === null &&+ input.localInitialTaskMode === "plan"+ ) {+ upload.start_in_plan_mode = true;+ }++ let agreed = local;+ let pull: boolean | null = null;+ const remote = server.auto_publish_cloud_runs;+ if (remote === null) {+ upload.auto_publish_cloud_runs = local;+ } else if (synced === undefined) {+ // First sync on this device: a value already on the server was chosen on purpose.+ agreed = remote;+ } else if (local !== synced.autoPublishCloudRuns) {+ upload.auto_publish_cloud_runs = local;+ } else {+ agreed = remote;+ }+ if (agreed !== local) {+ pull = agreed;+ }++ return {+ upload,+ pullAutoPublishCloudRuns: pull,+ synced: { autoPublishCloudRuns: agreed, planModeOffered: true },+ };+}diff --git a/products/desktop/packages/ui/src/features/settings/settings.module.ts b/products/desktop/packages/ui/src/features/settings/settings.module.tsindex 74877961dd5a..7ad8dc07dcf9 100644--- a/products/desktop/packages/ui/src/features/settings/settings.module.ts+++ b/products/desktop/packages/ui/src/features/settings/settings.module.ts@@ -7,6 +7,7 @@ import { CONTRIBUTION } from "@posthog/di/contribution";import { ContainerModule } from "inversify";import { CustomInstructionsSyncContribution } from "./customInstructionsSync.contribution";import { ServerAgentInstructionsContribution } from "./serverAgentInstructions.contribution";+import { ServerTaskDefaultsContribution } from "./serverTaskDefaults.contribution";import { settingsBackupState } from "./settingsBackupState";export const settingsUiModule = new ContainerModule(({ bind }) => {@@ -14,4 +15,5 @@ export const settingsUiModule = new ContainerModule(({ bind }) => {bind(SETTINGS_BACKUP_SERVICE).to(SettingsBackupService).inSingletonScope();bind(CONTRIBUTION).to(CustomInstructionsSyncContribution).inSingletonScope();bind(CONTRIBUTION).to(ServerAgentInstructionsContribution).inSingletonScope();+ bind(CONTRIBUTION).to(ServerTaskDefaultsContribution).inSingletonScope();});diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.tsindex 59eb192956af..0dc14ecec768 100644--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts@@ -128,6 +128,13 @@ export function countRetiredHints(hints: Record<string, HintState>): number {* from. Runtime-only: the sync contribution re-reads the file on boot and* whenever the toggle flips on.*/+export interface TaskDefaultsSyncState {+ // The "always create pull requests" value Desktop and the server last agreed on.+ autoPublishCloudRuns: boolean;+ // The local "Start in" choice was offered to the server once.+ planModeOffered: boolean;+}+export interface SyncedCustomInstructions {path: string;/** Home-relative form of `path` (e.g. `~/.claude/CLAUDE.md`), for display. */@@ -248,6 +255,9 @@ export interface SettingsStore {// Per project, the custom instructions text last uploaded to "My// instructions" on the server. Keyed by project id.customInstructionsOnServer: Record<string, string>;+ // Per project, what Desktop last synced with the task defaults on the+ // server. Keyed by project id.+ taskDefaultsOnServer: Record<string, TaskDefaultsSyncState>;setAutoConvertLongText: (value: AutoConvertLongText) => void;setSendMessagesWith: (mode: SendMessagesWith) => void;setCustomInstructions: (instructions: string) => void;@@ -257,6 +267,10 @@ export interface SettingsStore {synced: SyncedCustomInstructions | null,) => void;setCustomInstructionsOnServer: (projectId: number, content: string) => void;+ setTaskDefaultsOnServer: (+ projectId: number,+ synced: TaskDefaultsSyncState,+ ) => void;// Diff viewerdiffOpenMode: DiffOpenMode;@@ -533,6 +547,7 @@ export const useSettingsStore = create<SettingsStore>()(syncCustomInstructionsFromFile: false,syncedCustomInstructions: null,customInstructionsOnServer: {},+ taskDefaultsOnServer: {},setAutoConvertLongText: (value) => set({ autoConvertLongText: value }),setSendMessagesWith: (mode) => set({ sendMessagesWith: mode }),setCustomInstructions: (instructions) =>@@ -549,6 +564,13 @@ export const useSettingsStore = create<SettingsStore>()([String(projectId)]: content,},})),+ setTaskDefaultsOnServer: (projectId, synced) =>+ set((state) => ({+ taskDefaultsOnServer: {+ ...state.taskDefaultsOnServer,+ [String(projectId)]: synced,+ },+ })),// Diff viewerdiffOpenMode: "auto",@@ -751,6 +773,7 @@ export const useSettingsStore = create<SettingsStore>()(ste100Enabled: state.ste100Enabled,syncCustomInstructionsFromFile: state.syncCustomInstructionsFromFile,customInstructionsOnServer: state.customInstructionsOnServer,+ taskDefaultsOnServer: state.taskDefaultsOnServer,// Diff viewerdiffOpenMode: state.diffOpenMode,