: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 custom instructions to my instructions on the server behind a flag (#110400)
Shy Alter4cbebd8fa575
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 41bd78a9438e..4d831c4fc37c 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -2560,6 +2560,42 @@ export class PostHogAPIClient {).preferences;}+ /** The signed-in user's personal instructions for cloud runs in this project. Empty when unset. */+ async getMyAgentInstructions(projectId: number): Promise<string> {+ const urlPath = `/api/projects/${projectId}/tasks/@me/config/`;+ const response = await this.api.fetcher.fetch({+ method: "get",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ });+ if (!response.ok) {+ throw new Error(`Agent instructions request failed: ${response.status}`);+ }+ const payload = (await response.json()) as {+ agent_instructions?: string | null;+ };+ return payload.agent_instructions ?? "";+ }++ /** Replace the signed-in user's personal instructions for cloud runs in this project. */+ async setMyAgentInstructions(+ projectId: number,+ instructions: string,+ ): Promise<void> {+ const urlPath = `/api/projects/${projectId}/tasks/@me/config/agent_instructions/`;+ const response = await this.api.fetcher.fetch({+ method: "post",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ overrides: {+ body: JSON.stringify({ agent_instructions: instructions }),+ },+ });+ if (!response.ok) {+ throw new Error(`Agent instructions update failed: ${response.status}`);+ }+ }+private async taskRunConfigRequest(method: "get" | "post",urlPath: string,diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.jsonindex 74d2f456118d..f366bd7f56b9 100644--- a/products/desktop/packages/shared/src/feature-flag-keys.json+++ b/products/desktop/packages/shared/src/feature-flag-keys.json@@ -27,6 +27,7 @@"PROJECT_BLUEBIRD_FLAG": "project-bluebird","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","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 8dae8249ef09..17fedb08edcb 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -98,3 +98,6 @@ export const CUSTOM_IMAGES_FEATURE_FLAG =export const PI_HARNESS_FLAG = featureFlagKeys.PI_HARNESS_FLAG;export const TWIG_CLOUD_MODE_FLAG = featureFlagKeys.TWIG_CLOUD_MODE_FLAG;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;diff --git a/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.stories.tsxindex 220bb9e8d074..867437361d6a 100644--- a/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.stories.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.stories.tsx@@ -100,3 +100,13 @@ export const SyncOnNoFileFound: Story = {synced: null,},};++/** Cloud tasks use My instructions from PostHog: a note links there. */+export const CloudUsesMyInstructions: Story = {+ args: {+ instructions:+ "Always write tests for new code. Prefer functional patterns.",+ myInstructionsUrl:+ "https://us.posthog.com/project/1/settings/environment-task-agent-instructions",+ },+};diff --git a/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.tsxindex 4ab05f297a20..7d607b0c7ba0 100644--- a/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.tsx@@ -1,12 +1,17 @@import { buildPostHogUrl } from "@posthog/core/settings/posthogUrl";import { Switch, Textarea } from "@posthog/quill";-import { ANALYTICS_EVENTS } from "@posthog/shared";+import {+ ANALYTICS_EVENTS,+ SERVER_AGENT_INSTRUCTIONS_FLAG,+} from "@posthog/shared";import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import {SettingsCard,SettingsCardRow,SettingsSection,} from "@posthog/ui/features/settings/components/SettingsCard";+import { cloudTaskCarriesLocalInstructions } from "@posthog/ui/features/settings/serverAgentInstructions";import {type SyncedCustomInstructions,useSettingsStore,@@ -26,6 +31,8 @@ export interface PersonalizationSettingsViewProps {synced: SyncedCustomInstructions | null;ste100Enabled: boolean;onSte100Toggle: (checked: boolean) => void;+ /** Set once cloud tasks use "My instructions" from PostHog for this project. */+ myInstructionsUrl?: string | null;}// Pure render of the instructions block. The container below owns the store@@ -39,6 +46,7 @@ export function PersonalizationSettingsView({synced,ste100Enabled,onSte100Toggle,+ myInstructionsUrl,}: PersonalizationSettingsViewProps) {return (<SettingsSection@@ -109,6 +117,20 @@ export function PersonalizationSettingsView({)}</div></SettingsCard>+ {myInstructionsUrl && (+ <span className="text-[12px] text-muted-foreground">+ Cloud tasks use your My instructions from PostHog. Changes here apply+ to local tasks only.{" "}+ <a+ href={myInstructionsUrl}+ target="_blank"+ rel="noreferrer"+ className="text-accent-11 underline hover:text-accent-12"+ >+ Edit My instructions+ </a>+ </span>+ )}</SettingsSection>);}@@ -127,6 +149,26 @@ export function PersonalizationSettings() {const synced = useSettingsStore((s) => s.syncedCustomInstructions);const ste100Enabled = useSettingsStore((s) => s.ste100Enabled);const setSte100Enabled = useSettingsStore((s) => s.setSte100Enabled);+ const onServerProjectIds = useSettingsStore(+ (s) => s.customInstructionsOnServerProjectIds,+ );+ const serverInstructionsEnabled = useFeatureFlag(+ SERVER_AGENT_INSTRUCTIONS_FLAG,+ );+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);+ const myInstructionsUrl =+ projectId != null &&+ !cloudTaskCarriesLocalInstructions({+ flagEnabled: serverInstructionsEnabled,+ projectId,+ onServerProjectIds,+ })+ ? buildPostHogUrl(+ `/project/${projectId}/settings/environment-task-agent-instructions`,+ cloudRegion,+ )+ : null;// The draft renders over the store value only while edits are pending// (null = none), instead of copying the store into state and mirroring it@@ -194,6 +236,7 @@ export function PersonalizationSettings() {synced={synced}ste100Enabled={ste100Enabled}onSte100Toggle={handleSte100Toggle}+ myInstructionsUrl={myInstructionsUrl}/><FunSection /></div>diff --git a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.contribution.ts b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.contribution.tsnew file mode 100644index 000000000000..125662e30aec--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.contribution.ts@@ -0,0 +1,106 @@+import type { Contribution } from "@posthog/di/contribution";+import {+ HOST_TRPC_CLIENT,+ type HostTrpcClient,+} from "@posthog/host-router/client";+import { SERVER_AGENT_INSTRUCTIONS_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 {+ getEffectiveCustomInstructions,+ useSettingsStore,+} from "@posthog/ui/features/settings/settingsStore";+import { logger } from "@posthog/ui/shell/logger";+import { inject, injectable } from "inversify";+import { nextInstructionsMove } from "./serverAgentInstructions";++const log = logger.scope("server-agent-instructions");++/**+ * Adds the local custom instructions to "My instructions" on the server one+ * time per project, after any text already there. After that, the server adds+ * them to every cloud run, so cloud tasks stop carrying a local copy.+ */+@injectable()+export class ServerAgentInstructionsContribution implements Contribution {+ private readonly inFlight = new Set<number>();+ // Projects whose merged text is too long for the server. Cloud tasks keep+ // the local copy, and the next app start tries again.+ private readonly keptLocal = new Set<number>();++ constructor(+ @inject(HOST_TRPC_CLIENT)+ private readonly hostClient: HostTrpcClient,+ @inject(FEATURE_FLAGS)+ private readonly flags: FeatureFlags,+ ) {}++ start(): void {+ const run = () => void this.reconcile();+ this.flags.onFlagsLoaded(run);+ useSettingsStore.subscribe(run);+ useAuthStore.subscribe(run);+ run();+ }++ private async reconcile(): Promise<void> {+ if (!this.flags.isEnabled(SERVER_AGENT_INSTRUCTIONS_FLAG)) return;+ const settings = useSettingsStore.getState();+ const authState = useAuthStore.getState().authState;+ const projectId = authState.currentProjectId;+ if (!settings._hasHydrated || projectId == null) return;+ if (+ settings.customInstructionsOnServerProjectIds.includes(projectId) ||+ this.inFlight.has(projectId) ||+ this.keptLocal.has(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 local = getEffectiveCustomInstructions(settings);+ const server = await client.getMyAgentInstructions(projectId);+ const move = nextInstructionsMove({+ // With file sync on, wait for the file snapshot, or only the+ // Simplified Technical English line would move.+ localReady:+ !settings.syncCustomInstructionsFromFile ||+ settings.syncedCustomInstructions != null,+ local,+ server,+ });+ if (move.step === "wait") return;+ if (move.step === "keepLocal") {+ this.keptLocal.add(projectId);+ log.warn("Custom instructions are too long to move to the server");+ return;+ }+ if (move.step === "upload") {+ await client.setMyAgentInstructions(projectId, move.instructions);+ }+ useSettingsStore.getState().markCustomInstructionsOnServer(projectId);+ } catch (err) {+ // Cloud tasks keep the local copy, so a failed move changes nothing.+ log.warn("Failed to move custom instructions to the server", err);+ } finally {+ this.inFlight.delete(projectId);+ }+ }+}diff --git a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.ts b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.tsnew file mode 100644index 000000000000..e7ffc232ab5b--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import {+ cloudTaskCarriesLocalInstructions,+ nextInstructionsMove,+} from "./serverAgentInstructions";++describe("serverAgentInstructions", () => {+ it.each([+ [+ "the file snapshot is not loaded yet",+ false,+ "Use pnpm.",+ "",+ { step: "wait" },+ ],+ ["there is nothing local to move", true, " ", "Mine.", { step: "done" }],+ [+ "the server already has the local text",+ true,+ "Use pnpm.",+ "Mine.\n\nUse pnpm.",+ { step: "done" },+ ],+ [+ "only the local copy has instructions",+ true,+ " Use pnpm. ",+ "",+ { step: "upload", instructions: "Use pnpm." },+ ],+ [+ "both have different text",+ true,+ "Use pnpm.",+ "Mine.",+ { step: "upload", instructions: "Mine.\n\nUse pnpm." },+ ],+ [+ "the merged text is too long",+ true,+ "x".repeat(15_000),+ "y".repeat(6_000),+ { step: "keepLocal" },+ ],+ ] as const)("when %s", (_case, localReady, local, server, expected) => {+ expect(nextInstructionsMove({ localReady, local, server })).toEqual(+ expected,+ );+ });++ it.each([+ [false, 7, [7], true],+ [true, 7, [], true],+ [true, null, [7], true],+ [true, 7, [7], false],+ ] as const)(+ "flag %s, project %s, moved %j: carries local copy %s",+ (flagEnabled, projectId, onServerProjectIds, expected) => {+ expect(+ cloudTaskCarriesLocalInstructions({+ flagEnabled,+ projectId,+ onServerProjectIds,+ }),+ ).toBe(expected);+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.ts b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.tsnew file mode 100644index 000000000000..2f1c67703d08--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.ts@@ -0,0 +1,43 @@+/** The server limit for "My instructions". */+export const MAX_SERVER_AGENT_INSTRUCTIONS_LENGTH = 20_000;++export type InstructionsMove =+ | { step: "wait" }+ | { step: "done" }+ | { step: "keepLocal" }+ | { step: "upload"; instructions: string };++/**+ * What to do with the local custom instructions for one project. The result+ * keeps every instruction: text already on the server stays first, and the+ * local text follows it unless the server text already contains it.+ */+export function nextInstructionsMove(input: {+ localReady: boolean;+ local: string;+ server: string;+}): InstructionsMove {+ if (!input.localReady) return { step: "wait" };+ const local = input.local.trim();+ const server = input.server.trim();+ if (!local || server.includes(local)) return { step: "done" };+ const instructions = server ? `${server}\n\n${local}` : local;+ // Too long for the server: keep sending the local copy so nothing is lost.+ if (instructions.length > MAX_SERVER_AGENT_INSTRUCTIONS_LENGTH) {+ return { step: "keepLocal" };+ }+ return { step: "upload", instructions };+}++/** Cloud tasks carry a local copy only until the server holds the instructions. */+export function cloudTaskCarriesLocalInstructions(input: {+ flagEnabled: boolean;+ projectId: number | null;+ onServerProjectIds: readonly number[];+}): boolean {+ return !(+ input.flagEnabled &&+ input.projectId != null &&+ input.onServerProjectIds.includes(input.projectId)+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/settings.module.ts b/products/desktop/packages/ui/src/features/settings/settings.module.tsindex 76fd8051ee12..74877961dd5a 100644--- a/products/desktop/packages/ui/src/features/settings/settings.module.ts+++ b/products/desktop/packages/ui/src/features/settings/settings.module.ts@@ -6,10 +6,12 @@ import {import { CONTRIBUTION } from "@posthog/di/contribution";import { ContainerModule } from "inversify";import { CustomInstructionsSyncContribution } from "./customInstructionsSync.contribution";+import { ServerAgentInstructionsContribution } from "./serverAgentInstructions.contribution";import { settingsBackupState } from "./settingsBackupState";export const settingsUiModule = new ContainerModule(({ bind }) => {bind(SETTINGS_BACKUP_STATE).toConstantValue(settingsBackupState);bind(SETTINGS_BACKUP_SERVICE).to(SettingsBackupService).inSingletonScope();bind(CONTRIBUTION).to(CustomInstructionsSyncContribution).inSingletonScope();+ bind(CONTRIBUTION).to(ServerAgentInstructionsContribution).inSingletonScope();});diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.tsindex 7ef44179e486..f414301db6c7 100644--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts@@ -245,6 +245,9 @@ export interface SettingsStore {// instead of the hand-typed customInstructions above.syncCustomInstructionsFromFile: boolean;syncedCustomInstructions: SyncedCustomInstructions | null;+ // Projects where the custom instructions now live in "My instructions" on+ // the server, so cloud tasks no longer carry a local copy.+ customInstructionsOnServerProjectIds: number[];setAutoConvertLongText: (value: AutoConvertLongText) => void;setSendMessagesWith: (mode: SendMessagesWith) => void;setCustomInstructions: (instructions: string) => void;@@ -253,6 +256,7 @@ export interface SettingsStore {setSyncedCustomInstructions: (synced: SyncedCustomInstructions | null,) => void;+ markCustomInstructionsOnServer: (projectId: number) => void;// Diff viewerdiffOpenMode: DiffOpenMode;@@ -528,6 +532,7 @@ export const useSettingsStore = create<SettingsStore>()(ste100Enabled: true,syncCustomInstructionsFromFile: false,syncedCustomInstructions: null,+ customInstructionsOnServerProjectIds: [],setAutoConvertLongText: (value) => set({ autoConvertLongText: value }),setSendMessagesWith: (mode) => set({ sendMessagesWith: mode }),setCustomInstructions: (instructions) =>@@ -537,6 +542,17 @@ export const useSettingsStore = create<SettingsStore>()(set({ syncCustomInstructionsFromFile: enabled }),setSyncedCustomInstructions: (synced) =>set({ syncedCustomInstructions: synced }),+ markCustomInstructionsOnServer: (projectId) =>+ set((state) =>+ state.customInstructionsOnServerProjectIds.includes(projectId)+ ? state+ : {+ customInstructionsOnServerProjectIds: [+ ...state.customInstructionsOnServerProjectIds,+ projectId,+ ],+ },+ ),// Diff viewerdiffOpenMode: "auto",@@ -738,6 +754,8 @@ export const useSettingsStore = create<SettingsStore>()(customInstructions: state.customInstructions,ste100Enabled: state.ste100Enabled,syncCustomInstructionsFromFile: state.syncCustomInstructionsFromFile,+ customInstructionsOnServerProjectIds:+ state.customInstructionsOnServerProjectIds,// Diff viewerdiffOpenMode: state.diffOpenMode,diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.tsindex d2a12e5426aa..25d1d2d1c1e8 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts@@ -19,6 +19,7 @@ import {ANALYTICS_EVENTS,type ModelAccess,PROJECT_BLUEBIRD_FLAG,+ SERVER_AGENT_INSTRUCTIONS_FLAG,type TaskCreationInput,type WorkspaceMode,} from "@posthog/shared";@@ -63,6 +64,7 @@ import { useTaskInputHistoryStore } from "../../message-editor/taskInputHistorySimport type { EditorHandle } from "../../message-editor/types";import { toastError } from "../../notifications/errorDetails";import { useProvisioningStore } from "../../provisioning/store";+import { cloudTaskCarriesLocalInstructions } from "../../settings/serverAgentInstructions";import {getEffectiveCustomInstructions,useSettingsStore,@@ -269,6 +271,10 @@ export function useTaskCreation({PROJECT_BLUEBIRD_FLAG,import.meta.env.DEV,);+ const serverInstructionsEnabled = useFeatureFlag(+ SERVER_AGENT_INSTRUCTIONS_FLAG,+ );+ const currentProjectId = useAuthStateValue((state) => state.currentProjectId);const claudeTokenStore = useServiceOptional<ClaudeSubscriptionTokenSettings>(CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,);@@ -503,7 +509,16 @@ export function useTaskCreation({channelName,channelId: channelId ?? defaultedChannelId,channelContextId,- customInstructions: getEffectiveCustomInstructions(settings),+ customInstructions:+ workspaceMode === "cloud" &&+ !cloudTaskCarriesLocalInstructions({+ flagEnabled: serverInstructionsEnabled,+ projectId: currentProjectId,+ onServerProjectIds:+ settings.customInstructionsOnServerProjectIds,+ })+ ? undefined+ : getEffectiveCustomInstructions(settings),autoPublishCloudRuns: settings.autoPublishCloudRuns,rtkEnabledCloud: settings.rtkEnabledCloud,allowNoRepo,@@ -677,6 +692,8 @@ export function useTaskCreation({[canSubmit,canSubmitBase,+ serverInstructionsEnabled,+ currentProjectId,editorRef,sessionId,selectedDirectory,