: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): keep my instructions in step with desktop custom instructions (#110499)
Shy Alter0ee0740c79dc
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 867437361d6a..220bb9e8d074 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,13 +100,3 @@ 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 7d607b0c7ba0..4ab05f297a20 100644--- a/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/PersonalizationSettings.tsx@@ -1,17 +1,12 @@import { buildPostHogUrl } from "@posthog/core/settings/posthogUrl";import { Switch, Textarea } from "@posthog/quill";-import {- ANALYTICS_EVENTS,- SERVER_AGENT_INSTRUCTIONS_FLAG,-} from "@posthog/shared";+import { ANALYTICS_EVENTS } 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,@@ -31,8 +26,6 @@ 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@@ -46,7 +39,6 @@ export function PersonalizationSettingsView({synced,ste100Enabled,onSte100Toggle,- myInstructionsUrl,}: PersonalizationSettingsViewProps) {return (<SettingsSection@@ -117,20 +109,6 @@ 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>);}@@ -149,26 +127,6 @@ 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@@ -236,7 +194,6 @@ 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.tsindex 125662e30aec..75184d746745 100644--- a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.contribution.ts+++ b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.contribution.ts@@ -10,27 +10,28 @@ import {FEATURE_FLAGS,type FeatureFlags,} from "@posthog/ui/features/feature-flags/identifiers";-import {- getEffectiveCustomInstructions,- useSettingsStore,-} from "@posthog/ui/features/settings/settingsStore";+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { logger } from "@posthog/ui/shell/logger";import { inject, injectable } from "inversify";-import { nextInstructionsMove } from "./serverAgentInstructions";+import {+ getLocalInstructionsContent,+ nextServerInstructions,+} 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.+ * Keeps "My instructions" on the server in step with the Desktop custom+ * instructions for each project the person opens. The first upload adds the+ * text after any text already there. Later Desktop edits replace that part.+ * While the server holds the current text, cloud tasks do not carry a 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>();+ // The local text per project that is too long to merge on the server.+ // Cloud tasks keep the local copy until that text changes.+ private readonly keptLocal = new Map<number, string>();constructor(@inject(HOST_TRPC_CLIENT)@@ -53,10 +54,13 @@ export class ServerAgentInstructionsContribution implements Contribution {const authState = useAuthStore.getState().authState;const projectId = authState.currentProjectId;if (!settings._hasHydrated || projectId == null) return;+ const local = getLocalInstructionsContent(settings);+ if (local === null) return;+ const uploaded = settings.customInstructionsOnServer[String(projectId)];if (- settings.customInstructionsOnServerProjectIds.includes(projectId) ||+ uploaded === local ||this.inFlight.has(projectId) ||- this.keptLocal.has(projectId)+ this.keptLocal.get(projectId) === local) {return;}@@ -75,27 +79,25 @@ export class ServerAgentInstructionsContribution implements Contribution {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,+ const update = nextServerInstructions({server,+ previous: uploaded,+ local,});- if (move.step === "wait") return;- if (move.step === "keepLocal") {- this.keptLocal.add(projectId);+ if (update.step === "keepLocal") {+ this.keptLocal.set(projectId, local);log.warn("Custom instructions are too long to move to the server");return;}- if (move.step === "upload") {- await client.setMyAgentInstructions(projectId, move.instructions);+ if (update.step === "upload") {+ await client.setMyAgentInstructions(projectId, update.instructions);}- useSettingsStore.getState().markCustomInstructionsOnServer(projectId);+ // This store update runs reconcile again, which uploads an edit made+ // while this request was in flight.+ useSettingsStore+ .getState()+ .setCustomInstructionsOnServer(projectId, local);} 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);diff --git a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.ts b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.tsindex e7ffc232ab5b..3cd3d57700d0 100644--- a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.ts+++ b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.test.ts@@ -1,66 +1,103 @@import { describe, expect, it } from "vitest";import {cloudTaskCarriesLocalInstructions,- nextInstructionsMove,+ nextServerInstructions,} 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" }],+ ["nothing local to add", "Mine.", undefined, " ", { step: "done" }],["the server already has the local text",- true,- "Use pnpm.","Mine.\n\nUse pnpm.",+ undefined,+ "Use pnpm.",{ step: "done" },],[- "only the local copy has instructions",- true,- " Use pnpm. ",+ "only the local copy has text","",+ undefined,+ " Use pnpm. ",{ step: "upload", instructions: "Use pnpm." },],["both have different text",- true,- "Use pnpm.","Mine.",+ undefined,+ "Use pnpm.",{ step: "upload", instructions: "Mine.\n\nUse pnpm." },],+ [+ "a Desktop edit replaces the uploaded part",+ "Mine.\n\nUse pnpm.",+ "Use pnpm.",+ "Use npm.",+ { step: "upload", instructions: "Mine.\n\nUse npm." },+ ],+ [+ "a cleared Desktop text removes the uploaded part",+ "Mine.\n\nUse pnpm.",+ "Use pnpm.",+ "",+ { step: "upload", instructions: "Mine." },+ ],+ [+ "the uploaded part was removed on web",+ "Mine.",+ "Use pnpm.",+ "Use npm.",+ { step: "upload", instructions: "Mine.\n\nUse npm." },+ ],["the merged text is too long",- true,- "x".repeat(15_000),"y".repeat(6_000),+ undefined,+ "x".repeat(15_000),{ step: "keepLocal" },],- ] as const)("when %s", (_case, localReady, local, server, expected) => {- expect(nextInstructionsMove({ localReady, local, server })).toEqual(+ ] as const)("when %s", (_case, server, previous, local, expected) => {+ expect(nextServerInstructions({ server, previous, local })).toEqual(expected,);});it.each([- [false, 7, [7], true],- [true, 7, [], true],- [true, null, [7], true],- [true, 7, [7], false],+ ["the flag is off", false, 7, { "7": "Use pnpm." }, "Use pnpm.", true],+ ["nothing was uploaded", true, 7, {}, "Use pnpm.", true],+ [+ "the AGENTS.md snapshot is loading",+ true,+ 7,+ { "7": "Use pnpm." },+ null,+ true,+ ],+ [+ "a Desktop edit is not uploaded yet",+ true,+ 7,+ { "7": "Use pnpm." },+ "Use npm.",+ true,+ ],+ [+ "the server holds the current text",+ true,+ 7,+ { "7": "Use pnpm." },+ "Use pnpm.",+ false,+ ],] as const)(- "flag %s, project %s, moved %j: carries local copy %s",- (flagEnabled, projectId, onServerProjectIds, expected) => {+ "carries the local copy when %s: %s",+ (_case, flagEnabled, projectId, onServer, local, expected) => {expect(cloudTaskCarriesLocalInstructions({flagEnabled,projectId,- onServerProjectIds,+ onServer,+ local,}),).toBe(expected);},diff --git a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.ts b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.tsindex 2f1c67703d08..08255cbbf6e7 100644--- a/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.ts+++ b/products/desktop/packages/ui/src/features/settings/serverAgentInstructions.ts@@ -1,43 +1,79 @@+import type { SettingsStore } from "./settingsStore";+/** The server limit for "My instructions". */export const MAX_SERVER_AGENT_INSTRUCTIONS_LENGTH = 20_000;-export type InstructionsMove =- | { step: "wait" }+export type ServerInstructionsUpdate =| { 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.+ * The custom instructions text without the Simplified Technical English line,+ * which stays a separate switch. Null while the AGENTS.md snapshot is loading.*/-export function nextInstructionsMove(input: {- localReady: boolean;- local: string;+export function getLocalInstructionsContent(+ state: Pick<+ SettingsStore,+ | "customInstructions"+ | "syncCustomInstructionsFromFile"+ | "syncedCustomInstructions"+ >,+): string | null {+ if (!state.syncCustomInstructionsFromFile) {+ return state.customInstructions.trim();+ }+ return state.syncedCustomInstructions+ ? state.syncedCustomInstructions.content.trim()+ : null;+}++/**+ * The next "My instructions" text for one project. Desktop owns only the part+ * it uploaded: a new local text replaces that part, and any other text on the+ * server stays.+ */+export function nextServerInstructions(input: {server: string;-}): InstructionsMove {- if (!input.localReady) return { step: "wait" };- const local = input.local.trim();+ previous: string | undefined;+ local: string;+}): ServerInstructionsUpdate {const server = input.server.trim();- if (!local || server.includes(local)) return { step: "done" };- const instructions = server ? `${server}\n\n${local}` : local;+ const previous = input.previous?.trim() ?? "";+ const local = input.local.trim();+ let next: string;+ if (previous && server.includes(previous)) {+ next = server+ .replace(previous, () => local)+ .replace(/\n{3,}/g, "\n\n")+ .trim();+ } else if (!local || server.includes(local)) {+ next = server;+ } else {+ next = server ? `${server}\n\n${local}` : local;+ }+ if (next === server) return { step: "done" };// Too long for the server: keep sending the local copy so nothing is lost.- if (instructions.length > MAX_SERVER_AGENT_INSTRUCTIONS_LENGTH) {+ if (next.length > MAX_SERVER_AGENT_INSTRUCTIONS_LENGTH) {return { step: "keepLocal" };}- return { step: "upload", instructions };+ return { step: "upload", instructions: next };}-/** Cloud tasks carry a local copy only until the server holds the instructions. */+/**+ * Cloud tasks carry the local text until the server holds the current text.+ * A failed or pending upload keeps the local copy, so an edit is never lost.+ */export function cloudTaskCarriesLocalInstructions(input: {flagEnabled: boolean;projectId: number | null;- onServerProjectIds: readonly number[];+ onServer: Readonly<Record<string, string>>;+ local: string | null;}): boolean {return !(input.flagEnabled &&input.projectId != null &&- input.onServerProjectIds.includes(input.projectId)+ input.local != null &&+ input.onServer[String(input.projectId)] === input.local);}diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.tsindex f414301db6c7..59eb192956af 100644--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts@@ -245,9 +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[];+ // Per project, the custom instructions text last uploaded to "My+ // instructions" on the server. Keyed by project id.+ customInstructionsOnServer: Record<string, string>;setAutoConvertLongText: (value: AutoConvertLongText) => void;setSendMessagesWith: (mode: SendMessagesWith) => void;setCustomInstructions: (instructions: string) => void;@@ -256,7 +256,7 @@ export interface SettingsStore {setSyncedCustomInstructions: (synced: SyncedCustomInstructions | null,) => void;- markCustomInstructionsOnServer: (projectId: number) => void;+ setCustomInstructionsOnServer: (projectId: number, content: string) => void;// Diff viewerdiffOpenMode: DiffOpenMode;@@ -532,7 +532,7 @@ export const useSettingsStore = create<SettingsStore>()(ste100Enabled: true,syncCustomInstructionsFromFile: false,syncedCustomInstructions: null,- customInstructionsOnServerProjectIds: [],+ customInstructionsOnServer: {},setAutoConvertLongText: (value) => set({ autoConvertLongText: value }),setSendMessagesWith: (mode) => set({ sendMessagesWith: mode }),setCustomInstructions: (instructions) =>@@ -542,17 +542,13 @@ 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,- ],- },- ),+ setCustomInstructionsOnServer: (projectId, content) =>+ set((state) => ({+ customInstructionsOnServer: {+ ...state.customInstructionsOnServer,+ [String(projectId)]: content,+ },+ })),// Diff viewerdiffOpenMode: "auto",@@ -754,8 +750,7 @@ export const useSettingsStore = create<SettingsStore>()(customInstructions: state.customInstructions,ste100Enabled: state.ste100Enabled,syncCustomInstructionsFromFile: state.syncCustomInstructionsFromFile,- customInstructionsOnServerProjectIds:- state.customInstructionsOnServerProjectIds,+ customInstructionsOnServer: state.customInstructionsOnServer,// 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 25d1d2d1c1e8..e344ccfb33d0 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@@ -24,6 +24,7 @@ import {type WorkspaceMode,} from "@posthog/shared";import type { ExecutionMode, Task } from "@posthog/shared/domain-types";+import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION } from "@posthog/shared/product-engineer-prompt";import { getCurrentBrowserTabId } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { useTaskRepositoryDraftStore } from "@posthog/ui/features/canvas/stores/taskRepositoryDraftStore";@@ -64,7 +65,10 @@ 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 {+ cloudTaskCarriesLocalInstructions,+ getLocalInstructionsContent,+} from "../../settings/serverAgentInstructions";import {getEffectiveCustomInstructions,useSettingsStore,@@ -509,15 +513,19 @@ export function useTaskCreation({channelName,channelId: channelId ?? defaultedChannelId,channelContextId,+ // The server adds "My instructions" to cloud runs, so a cloud+ // task in sync carries only the Simplified Technical English line.customInstructions:workspaceMode === "cloud" &&!cloudTaskCarriesLocalInstructions({flagEnabled: serverInstructionsEnabled,projectId: currentProjectId,- onServerProjectIds:- settings.customInstructionsOnServerProjectIds,+ onServer: settings.customInstructionsOnServer,+ local: getLocalInstructionsContent(settings),})- ? undefined+ ? settings.ste100Enabled+ ? SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION+ : undefined: getEffectiveCustomInstructions(settings),autoPublishCloudRuns: settings.autoPublishCloudRuns,rtkEnabledCloud: settings.rtkEnabledCloud,