Skip to content

: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.

fix(desktop): name a task from the text pasted into the composer (#86703)

Phil Haack6bd40d946857
diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.ts
index 838fcb7d7637..2736d72bc835 100644
--- a/products/desktop/apps/code/src/renderer/di/bindings.ts
+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts
@@ -39,6 +39,10 @@ import {
EXTERNAL_APPS_WORKSPACE_CLIENT,
type ExternalAppsWorkspaceClient,
} from "@posthog/core/external-apps/identifiers";
+import {
+ FILE_READ_CLIENT,
+ type FileReadClient,
+} from "@posthog/core/files/identifiers";
import type {
GitInteractionEffects,
GitInteractionService,
@@ -107,12 +111,10 @@ import {
type SessionService,
} from "@posthog/core/sessions/sessionService";
import type {
- FileReadClient,
GithubPrTitleClient,
TitleGeneratorLogger,
} from "@posthog/core/sessions/titleGeneratorIdentifiers";
import {
- TITLE_GENERATOR_FILE_READ_CLIENT,
TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT,
TITLE_GENERATOR_LOGGER,
} from "@posthog/core/sessions/titleGeneratorIdentifiers";
@@ -352,7 +354,7 @@ export interface RendererBindings {
[CLOUD_ARTIFACT_RESOLVE_SKILL_DEPENDENCIES]: ResolveSkillBundleDependencies;
[CLOUD_ARTIFACT_READ_FILE_AS_BASE64]: ReadFileAsBase64;
[LLM_GATEWAY_SERVICE]: LlmGatewayService;
- [TITLE_GENERATOR_FILE_READ_CLIENT]: FileReadClient;
+ [FILE_READ_CLIENT]: FileReadClient;
[TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT]: GithubPrTitleClient;
[TITLE_GENERATOR_LOGGER]: TitleGeneratorLogger;
diff --git a/products/desktop/apps/code/src/renderer/di/container.ts b/products/desktop/apps/code/src/renderer/di/container.ts
index 998fb24fa1cb..6e84c0fab662 100644
--- a/products/desktop/apps/code/src/renderer/di/container.ts
+++ b/products/desktop/apps/code/src/renderer/di/container.ts
@@ -26,6 +26,7 @@ import {
EXTERNAL_APPS_WORKSPACE_CLIENT,
type ExternalAppsWorkspaceClient,
} from "@posthog/core/external-apps/identifiers";
+import { FILE_READ_CLIENT } from "@posthog/core/files/identifiers";
import { GitInteractionService } from "@posthog/core/git-interaction/gitInteractionService";
import {
GIT_INTERACTION_EFFECTS,
@@ -60,7 +61,6 @@ import {
} from "@posthog/core/sessions/sessionService";
import { sessionsModule } from "@posthog/core/sessions/sessions.module";
import {
- TITLE_GENERATOR_FILE_READ_CLIENT,
TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT,
TITLE_GENERATOR_LOGGER,
} from "@posthog/core/sessions/titleGeneratorIdentifiers";
@@ -505,7 +505,7 @@ container.bind(LLM_GATEWAY_SERVICE).toConstantValue({
model: options.model,
}),
} as unknown as LlmGatewayService);
-container.bind(TITLE_GENERATOR_FILE_READ_CLIENT).toConstantValue({
+container.bind(FILE_READ_CLIENT).toConstantValue({
readAbsoluteFile: (filePath: string) =>
trpcClient.fs.readAbsoluteFile.query({ filePath }),
});
diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.ts
index 4d0c28ce4204..a9668e6c2cfd 100644
--- a/products/desktop/apps/web/src/web-container.ts
+++ b/products/desktop/apps/web/src/web-container.ts
@@ -56,6 +56,10 @@ import {
type ExternalAppsFocusCoordinator,
type ExternalAppsWorkspaceClient,
} from "@posthog/core/external-apps/identifiers";
+import {
+ FILE_READ_CLIENT,
+ type FileReadClient,
+} from "@posthog/core/files/identifiers";
import { gitInteractionModule } from "@posthog/core/git-interaction/git-interaction.module";
import type {
GitInteractionEffects,
@@ -127,9 +131,7 @@ import {
} from "@posthog/core/sessions/sessionService";
import { sessionsModule } from "@posthog/core/sessions/sessions.module";
import {
- type FileReadClient,
type GithubPrTitleClient,
- TITLE_GENERATOR_FILE_READ_CLIENT,
TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT,
TITLE_GENERATOR_LOGGER,
TITLE_GENERATOR_SERVICE,
@@ -324,10 +326,10 @@ import { WebOAuthFlowService } from "./web-oauth-flow";
import { webDiffWorkerFactory, webReviewHost } from "./web-review-host";
import {
webBundleLocalSkill,
+ webFileReadClient,
webGithubPrTitleClient,
webReadFileAsBase64,
webResolveSkillBundleDependencies,
- webTitleGeneratorFileReadClient,
webTitleGeneratorLogger,
} from "./web-sessions-clients";
import { webSetupStore } from "./web-setup-store";
@@ -401,7 +403,7 @@ interface WebBindings {
[CLOUD_ARTIFACT_BUNDLE_LOCAL_SKILL]: BundleLocalSkill;
[CLOUD_ARTIFACT_RESOLVE_SKILL_DEPENDENCIES]: ResolveSkillBundleDependencies;
[TITLE_GENERATOR_SERVICE]: TitleGeneratorService;
- [TITLE_GENERATOR_FILE_READ_CLIENT]: FileReadClient;
+ [FILE_READ_CLIENT]: FileReadClient;
[TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT]: GithubPrTitleClient;
[TITLE_GENERATOR_LOGGER]: TitleGeneratorLogger;
[LLM_GATEWAY_SERVICE]: LlmGatewayService;
@@ -741,9 +743,7 @@ container
container
.bind(CLOUD_ARTIFACT_RESOLVE_SKILL_DEPENDENCIES)
.toConstantValue(webResolveSkillBundleDependencies);
-container
- .bind(TITLE_GENERATOR_FILE_READ_CLIENT)
- .toConstantValue(webTitleGeneratorFileReadClient);
+container.bind(FILE_READ_CLIENT).toConstantValue(webFileReadClient);
container
.bind(TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT)
.toConstantValue(webGithubPrTitleClient);
diff --git a/products/desktop/apps/web/src/web-sessions-clients.ts b/products/desktop/apps/web/src/web-sessions-clients.ts
index bf3174ad6c36..38e3712252a0 100644
--- a/products/desktop/apps/web/src/web-sessions-clients.ts
+++ b/products/desktop/apps/web/src/web-sessions-clients.ts
@@ -1,10 +1,11 @@
import type { ReadFileAsBase64 } from "@posthog/core/editor/cloud-prompt";
+import { base64ToText } from "@posthog/core/files/base64";
+import type { FileReadClient } from "@posthog/core/files/identifiers";
import type {
BundleLocalSkill,
ResolveSkillBundleDependencies,
} from "@posthog/core/sessions/cloudArtifactIdentifiers";
import type {
- FileReadClient,
GithubPrTitleClient,
TitleGeneratorLogger,
} from "@posthog/core/sessions/titleGeneratorIdentifiers";
@@ -84,10 +85,23 @@ export const webBundleLocalSkill: BundleLocalSkill = async (ref) => {
export const webResolveSkillBundleDependencies: ResolveSkillBundleDependencies =
(refs) => Promise.resolve(refs);
-// Title generator reads referenced files to enrich the title prompt; none exist
-// locally on web.
-export const webTitleGeneratorFileReadClient: FileReadClient = {
- readAbsoluteFile: () => Promise.resolve(null),
+// Naming a task reads the text a user pasted or dropped into the composer. Web
+// has no filesystem, but that text is already in the attachment store under the
+// same synthetic id, so decode it back from the stored bytes. Anything not in
+// the store — a real path carried by a cloud task made on desktop — stays
+// unreadable here.
+export const webFileReadClient: FileReadClient = {
+ readAbsoluteFile: (filePath: string) => {
+ const base64 = getWebAttachmentBase64(filePath);
+ if (!base64) {
+ return Promise.resolve(null);
+ }
+ try {
+ return Promise.resolve(base64ToText(base64));
+ } catch {
+ return Promise.resolve(null);
+ }
+ },
};
export function webTitleGeneratorLogger(
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index ade886423c4f..e6a1cd3fdd22 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -2532,6 +2532,7 @@ export class PostHogAPIClient {
pending_user_message?: string;
pending_user_artifact_ids?: string[];
auto_publish?: boolean;
+ naming_source?: string;
},
): Promise<Task> {
const teamId = await this.getTeamId();
diff --git a/products/desktop/packages/core/src/editor/cloud-prompt.ts b/products/desktop/packages/core/src/editor/cloud-prompt.ts
index 553f06dcd12b..de1f58f312c5 100644
--- a/products/desktop/packages/core/src/editor/cloud-prompt.ts
+++ b/products/desktop/packages/core/src/editor/cloud-prompt.ts
@@ -13,10 +13,46 @@ import {
serializeCloudPrompt,
unescapeXmlAttr,
} from "@posthog/shared";
+import type { EditorContent } from "../message-editor/content";
import { skillTagsToSlashCommands } from "../message-editor/skillTags";
export type ReadFileAsBase64 = (filePath: string) => Promise<string | null>;
+// The prefix every synthesized attachment summary starts with. Kept as the one
+// source of truth so the producer and the sentinel matchers below can never
+// drift apart on a rename.
+export const ATTACHMENT_SUMMARY_PREFIX = "Attached files: ";
+
+// Every form of the attachment-summary sentinel we synthesize for prompts that
+// carry no typed text. Three need stripping:
+// "Attached files: a.txt" — bare description (cloud task.description)
+// "[Attached files: a.txt]" — bracketed session-event sentinel
+// "1. [Attached files: a.txt]" — numbered form from formatPromptsForTitleInput
+// The bracketed forms require a literal `[` so that user text like
+// "1. Attached files: my notes" (no brackets) is never stripped.
+const ATTACHMENT_SUMMARY_LINE_REGEX = new RegExp(
+ `^(?:(?:\\d+\\.\\s*)?\\[${ATTACHMENT_SUMMARY_PREFIX}[^\\]]*\\]|${ATTACHMENT_SUMMARY_PREFIX}.*)$`,
+ "gm",
+);
+const EMPTY_NUMBERED_LINE_REGEX = /^\d+\.\s*$/gm;
+
+/**
+ * True when the content says something beyond naming its own attachments. File
+ * chips are dropped rather than rendered, because a chip's label is a filename
+ * and would otherwise read as prose. Takes already-parsed content so a caller
+ * that also needs the segments does not parse the same string twice.
+ */
+export function hasProseBeyondAttachments(content: EditorContent): boolean {
+ return (
+ content.segments
+ .flatMap((seg) => (seg.type === "text" ? [seg.text] : []))
+ .join("")
+ .replace(ATTACHMENT_SUMMARY_LINE_REGEX, "")
+ .replace(EMPTY_NUMBERED_LINE_REGEX, "")
+ .trim().length > 0
+ );
+}
+
const ABSOLUTE_FILE_TAG_REGEX = /<file\s+path="([^"]+)"\s*\/>/g;
const FOLDER_TAG_REGEX = /<folder\s+path="[^"]+"\s*\/>/g;
const FOLDER_TAG_PATH_REGEX = /<folder\s+path="([^"]+)"\s*\/>/g;
@@ -142,7 +178,6 @@ export function getAbsoluteAttachmentPaths(
);
}
-export const ATTACHMENT_SUMMARY_PREFIX = "Attached files: ";
const TRAILING_ATTACHMENT_SUMMARY_REGEX = new RegExp(
`(?:^|\\n)${ATTACHMENT_SUMMARY_PREFIX}[^\\n]*$`,
);
diff --git a/products/desktop/packages/core/src/files/attachmentText.ts b/products/desktop/packages/core/src/files/attachmentText.ts
new file mode 100644
index 000000000000..d6eb9d246f23
--- /dev/null
+++ b/products/desktop/packages/core/src/files/attachmentText.ts
@@ -0,0 +1,42 @@
+import { getFileName, isBinaryFile } from "@posthog/shared";
+import type { FileReadClient } from "./identifiers";
+
+/** Enough of an attachment to name a task after, without bloating the prompt. */
+export const ATTACHMENT_SNIPPET_LIMIT = 500;
+
+export interface AttachmentSnippet {
+ fileName: string;
+ /** Head of the file, or null when it is binary or could not be read. */
+ text: string | null;
+}
+
+export async function readAttachmentSnippets(
+ filePaths: string[],
+ fileReadClient: FileReadClient,
+): Promise<AttachmentSnippet[]> {
+ return Promise.all(
+ filePaths.map(async (filePath) => {
+ const fileName = getFileName(filePath);
+ if (isBinaryFile(filePath)) {
+ return { fileName, text: null };
+ }
+ try {
+ const content = await fileReadClient.readAbsoluteFile(filePath);
+ return {
+ fileName,
+ text: content ? content.slice(0, ATTACHMENT_SNIPPET_LIMIT) : null,
+ };
+ } catch {
+ return { fileName, text: null };
+ }
+ }),
+ );
+}
+
+export function formatAttachmentSnippet(snippet: AttachmentSnippet): string {
+ // Fall back to the file name for a binary, unreadable, or blank attachment: a
+ // name reads better than nothing when it is all we have to title a task with.
+ return snippet.text?.trim()
+ ? snippet.text
+ : `[Attached: ${snippet.fileName}]`;
+}
diff --git a/products/desktop/packages/core/src/files/base64.test.ts b/products/desktop/packages/core/src/files/base64.test.ts
new file mode 100644
index 000000000000..a4e7f229c1d8
--- /dev/null
+++ b/products/desktop/packages/core/src/files/base64.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { base64ToText } from "./base64";
+
+const encode = (text: string): string =>
+ Buffer.from(text, "utf-8").toString("base64");
+
+describe("base64ToText", () => {
+ it.each([
+ ["ascii", "Deploy blocks on a stale lockfile"],
+ ["multi-byte utf-8", "café — déjà vu 🚀 日本語"],
+ ["multi-line", "first line\nsecond line\n"],
+ ["empty", ""],
+ ])("round-trips %s content", (_name, text) => {
+ expect(base64ToText(encode(text))).toBe(text);
+ });
+});
diff --git a/products/desktop/packages/core/src/files/base64.ts b/products/desktop/packages/core/src/files/base64.ts
new file mode 100644
index 000000000000..84c9d4d89c54
--- /dev/null
+++ b/products/desktop/packages/core/src/files/base64.ts
@@ -0,0 +1,14 @@
+export function base64ToUint8Array(base64: string): Uint8Array<ArrayBuffer> {
+ const binary = atob(base64);
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
+
+ for (let index = 0; index < binary.length; index += 1) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+
+ return bytes;
+}
+
+export function base64ToText(base64: string): string {
+ return new TextDecoder().decode(base64ToUint8Array(base64));
+}
diff --git a/products/desktop/packages/core/src/files/identifiers.ts b/products/desktop/packages/core/src/files/identifiers.ts
new file mode 100644
index 000000000000..eb41cd9205b9
--- /dev/null
+++ b/products/desktop/packages/core/src/files/identifiers.ts
@@ -0,0 +1,5 @@
+export interface FileReadClient {
+ readAbsoluteFile(filePath: string): Promise<string | null>;
+}
+
+export const FILE_READ_CLIENT = Symbol.for("posthog.core.files.fileReadClient");
diff --git a/products/desktop/packages/core/src/sessions/cloudArtifactService.ts b/products/desktop/packages/core/src/sessions/cloudArtifactService.ts
index ddc333ad78a9..0582af4e8649 100644
--- a/products/desktop/packages/core/src/sessions/cloudArtifactService.ts
+++ b/products/desktop/packages/core/src/sessions/cloudArtifactService.ts
@@ -1,4 +1,5 @@
import type { ReadFileAsBase64 } from "@posthog/core/editor/cloud-prompt";
+import { base64ToUint8Array } from "@posthog/core/files/base64";
import { getFileName } from "@posthog/shared";
import { inject, injectable } from "inversify";
import {
@@ -67,17 +68,6 @@ interface LoadedCloudAttachment {
upload: CloudArtifactUploadRequest;
}
-function base64ToUint8Array(base64: string): Uint8Array<ArrayBuffer> {
- const binary = atob(base64);
- const bytes = new Uint8Array(new ArrayBuffer(binary.length));
-
- for (let index = 0; index < binary.length; index += 1) {
- bytes[index] = binary.charCodeAt(index);
- }
-
- return bytes;
-}
-
function getFileExtension(filePath: string): string {
const parts = getFileName(filePath).split(".");
return parts.length > 1 ? (parts.at(-1)?.toLowerCase() ?? "") : "";
diff --git a/products/desktop/packages/core/src/sessions/titleGeneratorIdentifiers.ts b/products/desktop/packages/core/src/sessions/titleGeneratorIdentifiers.ts
index eacf50c1c999..61964f987866 100644
--- a/products/desktop/packages/core/src/sessions/titleGeneratorIdentifiers.ts
+++ b/products/desktop/packages/core/src/sessions/titleGeneratorIdentifiers.ts
@@ -1,7 +1,3 @@
-export interface FileReadClient {
- readAbsoluteFile(filePath: string): Promise<string | null>;
-}
-
export interface GithubPrTitleClient {
getGithubPullRequestTitle(input: {
owner: string;
@@ -17,9 +13,6 @@ export interface TitleGeneratorLogger {
export const TITLE_GENERATOR_SERVICE = Symbol.for(
"posthog.core.sessions.titleGeneratorService",
);
-export const TITLE_GENERATOR_FILE_READ_CLIENT = Symbol.for(
- "posthog.core.sessions.titleGeneratorFileReadClient",
-);
export const TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT = Symbol.for(
"posthog.core.sessions.titleGeneratorGithubPrTitleClient",
);
diff --git a/products/desktop/packages/core/src/sessions/titleGeneratorService.test.ts b/products/desktop/packages/core/src/sessions/titleGeneratorService.test.ts
index ca2ef781e242..03ba84f3e35c 100644
--- a/products/desktop/packages/core/src/sessions/titleGeneratorService.test.ts
+++ b/products/desktop/packages/core/src/sessions/titleGeneratorService.test.ts
@@ -1,6 +1,6 @@
+import type { FileReadClient } from "@posthog/core/files/identifiers";
import type { LlmGatewayService } from "@posthog/core/llm-gateway/llm-gateway";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { FileReadClient } from "./titleGeneratorIdentifiers";
import { TitleGeneratorService } from "./titleGeneratorService";
const readAbsoluteFile = vi.fn<FileReadClient["readAbsoluteFile"]>();
diff --git a/products/desktop/packages/core/src/sessions/titleGeneratorService.ts b/products/desktop/packages/core/src/sessions/titleGeneratorService.ts
index d39b2f271ee5..474eded77300 100644
--- a/products/desktop/packages/core/src/sessions/titleGeneratorService.ts
+++ b/products/desktop/packages/core/src/sessions/titleGeneratorService.ts
@@ -1,3 +1,12 @@
+import { hasProseBeyondAttachments } from "@posthog/core/editor/cloud-prompt";
+import {
+ formatAttachmentSnippet,
+ readAttachmentSnippets,
+} from "@posthog/core/files/attachmentText";
+import {
+ FILE_READ_CLIENT,
+ type FileReadClient,
+} from "@posthog/core/files/identifiers";
import { LLM_GATEWAY_SERVICE } from "@posthog/core/llm-gateway/identifiers";
import {
HELPER_GATEWAY_MODEL,
@@ -7,28 +16,15 @@ import { xmlToContent } from "@posthog/core/message-editor/content";
import { isLoadingGithubRefTitle } from "@posthog/core/message-editor/githubIssueChip";
import { parseGithubIssueUrl } from "@posthog/core/message-editor/githubIssueUrl";
import { parseXmlAttrs } from "@posthog/core/message-editor/skillTags";
-import { escapeXmlAttr, getFileName, isBinaryFile } from "@posthog/shared";
+import { escapeXmlAttr } from "@posthog/shared";
import { inject, injectable } from "inversify";
import {
- type FileReadClient,
type GithubPrTitleClient,
- TITLE_GENERATOR_FILE_READ_CLIENT,
TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT,
TITLE_GENERATOR_LOGGER,
type TitleGeneratorLogger,
} from "./titleGeneratorIdentifiers";
-// Matches the attachment-summary sentinel we synthesize for prompts that carry
-// no typed text. Three forms need stripping:
-// "Attached files: a.txt" — bare description (cloud task.description)
-// "[Attached files: a.txt]" — bracketed session-event sentinel
-// "1. [Attached files: a.txt]" — numbered form from formatPromptsForTitleInput
-// The bracketed forms require a literal `[` so that user text like
-// "1. Attached files: my notes" (no brackets) is never stripped.
-const ATTACHED_FILES_REGEX =
- /^(?:(?:\d+\.\s*)?\[Attached files:[^\]]*\]|Attached files:.*)$/gm;
-const PASTED_TEXT_SNIPPET_LIMIT = 500;
-
interface GithubPrGenerationContext {
content: string;
deterministicTitle: string | null;
@@ -213,7 +209,7 @@ export class TitleGeneratorService {
constructor(
@inject(LLM_GATEWAY_SERVICE)
private readonly llmGateway: LlmGatewayService,
- @inject(TITLE_GENERATOR_FILE_READ_CLIENT)
+ @inject(FILE_READ_CLIENT)
private readonly fileReadClient: FileReadClient,
@inject(TITLE_GENERATOR_GITHUB_PR_TITLE_CLIENT)
private readonly githubPrTitleClient: GithubPrTitleClient,
@@ -226,14 +222,7 @@ export class TitleGeneratorService {
filePaths: string[] = [],
): Promise<string> {
const parsed = xmlToContent(description);
- const stripped = parsed.segments
- .flatMap((seg) => (seg.type === "text" ? [seg.text] : []))
- .join("")
- .replace(ATTACHED_FILES_REGEX, "")
- .replace(/^\d+\.\s*$/gm, "")
- .trim();
-
- if (stripped.length > 0) return description;
+ if (hasProseBeyondAttachments(parsed)) return description;
const chipFilePaths = parsed.segments.flatMap((seg) =>
seg.type === "chip" && seg.chip.type === "file" ? [seg.chip.id] : [],
@@ -242,25 +231,8 @@ export class TitleGeneratorService {
if (paths.length === 0) return description;
- const parts = await Promise.all(
- paths.map(async (filePath) => {
- if (isBinaryFile(filePath)) {
- return `[Attached: ${getFileName(filePath)}]`;
- }
- try {
- const fileContent =
- await this.fileReadClient.readAbsoluteFile(filePath);
- if (fileContent) {
- return fileContent.length > PASTED_TEXT_SNIPPET_LIMIT
- ? fileContent.slice(0, PASTED_TEXT_SNIPPET_LIMIT)
- : fileContent;
- }
- return `[Attached: ${getFileName(filePath)}]`;
- } catch {
- return `[Attached: ${getFileName(filePath)}]`;
- }
- }),
- );
+ const snippets = await readAttachmentSnippets(paths, this.fileReadClient);
+ const parts = snippets.map(formatAttachmentSnippet);
return parts.length > 0 ? parts.join("\n\n") : description;
}
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
index 872d8534abe9..54bf99f880c3 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -47,6 +47,8 @@ const piRunner = {
stop: vi.fn(async () => {}),
};
+const fileReadClient = { readAbsoluteFile: vi.fn(async () => null) };
+
const sessionService = {
connectToTask: vi.fn(),
disconnectFromTask: vi.fn(),
@@ -103,6 +105,7 @@ function makeSaga(
host,
sessionService,
piRunner,
+ fileReadClient,
track: vi.fn(),
...extra,
});
@@ -263,6 +266,7 @@ describe("TaskCreationSaga", () => {
host,
sessionService,
piRunner,
+ fileReadClient,
track: vi.fn(),
});
@@ -314,6 +318,7 @@ describe("TaskCreationSaga", () => {
host,
sessionService,
piRunner,
+ fileReadClient,
track: vi.fn(),
});
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index 7301dc0c09d3..7c00e8e4e082 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -19,6 +19,7 @@ import {
} from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import type { Task } from "@posthog/shared/domain-types";
+import type { FileReadClient } from "../files/identifiers";
import type { PiRunner } from "../pi-runtime/piRunner";
import type { TaskCreationApiClient } from "./taskCreationApiClient";
import type {
@@ -26,6 +27,7 @@ import type {
ImportedClaudeCliSession,
ITaskCreationHost,
} from "./taskCreationHost";
+import { buildTaskNamingSource } from "./taskDescription";
import { resolveTaskRepository } from "./taskRepository";
export interface TaskCreationDeps {
@@ -33,6 +35,7 @@ export interface TaskCreationDeps {
host: ITaskCreationHost;
sessionService: SessionService;
piRunner: PiRunner;
+ fileReadClient: FileReadClient;
onTaskReady?: (output: TaskCreationOutput) => void;
track: (event: string, props?: Record<string, unknown>) => void;
}
@@ -797,10 +800,16 @@ export class TaskCreationSaga extends Saga<
name: "task_creation",
execute: async () => {
const description = input.taskDescription ?? input.content ?? "";
+ const namingSource = await buildTaskNamingSource(
+ description,
+ input.filePaths ?? [],
+ this.deps.fileReadClient,
+ );
const canActivateWarmRun =
input.runtime !== "pi" && !warmPayload?.suppressWarmReuse;
const result = await this.deps.posthogClient.createTask({
description,
+ naming_source: namingSource,
repository: input.repositories
? undefined
: (repository ?? undefined),
diff --git a/products/desktop/packages/core/src/task-detail/taskDescription.test.ts b/products/desktop/packages/core/src/task-detail/taskDescription.test.ts
new file mode 100644
index 000000000000..0c38ebae47f5
--- /dev/null
+++ b/products/desktop/packages/core/src/task-detail/taskDescription.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+import { buildTaskNamingSource } from "./taskDescription";
+
+const PASTED = "/tmp/clip/attachment-a1b2c3/pasted-text.txt";
+const SHOT = "/tmp/clip/attachment-d4e5f6/shot.png";
+const NOTES = "/tmp/clip/attachment-j0k1l2/notes.txt";
+const BLANK = "/tmp/clip/attachment-m3n4o5/blank.txt";
+const GONE = "/tmp/clip/attachment-g7h8i9/gone.txt";
+
+const files: Record<string, string> = {
+ [PASTED]: "Deploy blocks on a stale lockfile\nSecond line",
+ [NOTES]: "Extra context line",
+ [BLANK]: " ",
+};
+
+const fileReadClient = {
+ readAbsoluteFile: (filePath: string) =>
+ Promise.resolve(files[filePath] ?? null),
+};
+
+describe("buildTaskNamingSource", () => {
+ it.each([
+ [
+ "names from pasted text behind a cloud attachment summary",
+ "Attached files: pasted-text.txt",
+ [PASTED],
+ "Deploy blocks on a stale lockfile\nSecond line",
+ ],
+ [
+ "names from pasted text behind a local file tag",
+ `<file path="${PASTED}" />`,
+ [PASTED],
+ "Deploy blocks on a stale lockfile\nSecond line",
+ ],
+ [
+ "joins multiple readable files",
+ "Attached files: pasted-text.txt, notes.txt",
+ [PASTED, NOTES],
+ "Deploy blocks on a stale lockfile\nSecond line\n\nExtra context line",
+ ],
+ [
+ "falls back to the file name for a binary attachment",
+ "Attached files: shot.png",
+ [SHOT],
+ "[Attached: shot.png]",
+ ],
+ [
+ "falls back to the file name for an unreadable attachment",
+ "Attached files: gone.txt",
+ [GONE],
+ "[Attached: gone.txt]",
+ ],
+ [
+ "falls back to the file name for a whitespace-only attachment",
+ "Attached files: blank.txt",
+ [BLANK],
+ "[Attached: blank.txt]",
+ ],
+ ])("%s", async (_name, description, filePaths, expected) => {
+ await expect(
+ buildTaskNamingSource(description, filePaths, fileReadClient),
+ ).resolves.toBe(expected);
+ });
+
+ it.each([
+ ["a typed prompt", "Fix the login redirect", [PASTED]],
+ [
+ "a typed prompt with an attachment summary",
+ "Fix the login redirect\n\nAttached files: pasted-text.txt",
+ [PASTED],
+ ],
+ ["no attachments", "Attached files: pasted-text.txt", []],
+ ])("returns undefined for %s", async (_name, description, filePaths) => {
+ await expect(
+ buildTaskNamingSource(description, filePaths, fileReadClient),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/products/desktop/packages/core/src/task-detail/taskDescription.ts b/products/desktop/packages/core/src/task-detail/taskDescription.ts
new file mode 100644
index 000000000000..258109e0639e
--- /dev/null
+++ b/products/desktop/packages/core/src/task-detail/taskDescription.ts
@@ -0,0 +1,39 @@
+import { hasProseBeyondAttachments } from "@posthog/core/editor/cloud-prompt";
+import {
+ formatAttachmentSnippet,
+ readAttachmentSnippets,
+} from "@posthog/core/files/attachmentText";
+import type { FileReadClient } from "@posthog/core/files/identifiers";
+import { xmlToContent } from "@posthog/core/message-editor/content";
+
+/**
+ * Build the text the server should name a task from, when the description has no
+ * prose of its own.
+ *
+ * Pasting a block of text into the composer stores it as a `pasted-text.txt`
+ * attachment, so the description reaching the API is only an `Attached files:`
+ * summary (cloud) or a bare `<file />` tag (local). Naming a task from that alone
+ * gives "Untitled". This reads the head of each attachment and returns it as a
+ * separate naming source, leaving the description (the agent prompt, and the key
+ * the reload transcript dedup matches on) untouched.
+ *
+ * Returns `undefined` when the description already carries prose, so the server
+ * names from the description as before.
+ */
+export async function buildTaskNamingSource(
+ description: string,
+ filePaths: string[],
+ fileReadClient: FileReadClient,
+): Promise<string | undefined> {
+ if (
+ filePaths.length === 0 ||
+ hasProseBeyondAttachments(xmlToContent(description))
+ ) {
+ return undefined;
+ }
+
+ const snippets = await readAttachmentSnippets(filePaths, fileReadClient);
+ const namingSource = snippets.map(formatAttachmentSnippet).join("\n\n");
+
+ return namingSource.trim() ? namingSource : undefined;
+}
diff --git a/products/desktop/packages/core/src/task-detail/taskService.test.ts b/products/desktop/packages/core/src/task-detail/taskService.test.ts
index 5b614c0c0f04..fc0145f3232c 100644
--- a/products/desktop/packages/core/src/task-detail/taskService.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskService.test.ts
@@ -18,6 +18,8 @@ const rootLogger = {
scope: () => scopedLog,
} as unknown as RootLogger;
+const fileReadClient = { readAbsoluteFile: vi.fn(async () => null) };
+
function makeService(): TaskService {
const host = {
// The API client's createTask rejects so tests can observe that an input
@@ -51,7 +53,14 @@ function makeService(): TaskService {
resume: vi.fn(),
stop: vi.fn(),
} as unknown as PiRunner;
- return new TaskService(host, sessionService, effects, piRunner, rootLogger);
+ return new TaskService(
+ host,
+ sessionService,
+ effects,
+ piRunner,
+ fileReadClient,
+ rootLogger,
+ );
}
describe("TaskService.openTask", () => {
@@ -80,6 +89,7 @@ describe("TaskService.openTask", () => {
{} as SessionService,
{} as TaskCreationEffects,
piRunner,
+ fileReadClient,
rootLogger,
);
@@ -123,6 +133,7 @@ describe("TaskService.openTask", () => {
{} as SessionService,
{} as TaskCreationEffects,
piRunner,
+ fileReadClient,
rootLogger,
);
@@ -159,6 +170,7 @@ describe("TaskService.resumeCloudPiRun", () => {
{} as SessionService,
effects,
{} as PiRunner,
+ fileReadClient,
rootLogger,
);
diff --git a/products/desktop/packages/core/src/task-detail/taskService.ts b/products/desktop/packages/core/src/task-detail/taskService.ts
index fbcf5e8aeb7e..ae38b49fc3f1 100644
--- a/products/desktop/packages/core/src/task-detail/taskService.ts
+++ b/products/desktop/packages/core/src/task-detail/taskService.ts
@@ -14,6 +14,7 @@ import type {
} from "@posthog/shared";
import type { Task, TaskRun } from "@posthog/shared/domain-types";
import { inject, injectable } from "inversify";
+import { FILE_READ_CLIENT, type FileReadClient } from "../files/identifiers";
import { extractFilePaths, xmlToContent } from "../message-editor/content";
import { PI_RUNNER } from "../pi-runtime/identifiers";
import type { PiRunner } from "../pi-runtime/piRunner";
@@ -50,6 +51,8 @@ export class TaskService {
private readonly effects: TaskCreationEffects,
@inject(PI_RUNNER)
private readonly piRunner: PiRunner,
+ @inject(FILE_READ_CLIENT)
+ private readonly fileReadClient: FileReadClient,
@inject(ROOT_LOGGER)
rootLogger: RootLogger,
) {
@@ -156,6 +159,7 @@ export class TaskService {
host: this.host,
sessionService: this.sessionService,
piRunner: this.piRunner,
+ fileReadClient: this.fileReadClient,
track: (event, props) => this.host.track(event, props),
onTaskReady,
},
@@ -301,6 +305,7 @@ export class TaskService {
host: this.host,
sessionService: this.sessionService,
piRunner: this.piRunner,
+ fileReadClient: this.fileReadClient,
track: (event, props) => this.host.track(event, props),
},
this.log,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 0c517e103f00..ddf492eac794 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5307,6 +5307,9 @@ def create_task(
pending_user_message = (validated_data.pop("pending_user_message", None) or "").strip() or None
pending_user_artifact_ids = validated_data.pop("pending_user_artifact_ids", None) or []
warm_auto_publish = validated_data.pop("auto_publish", None)
+ # Names the task from the pasted content while `description` stays the bare prompt. Write-only,
+ # never persisted, so it must be popped before `Task.objects.create(**validated_data)`.
+ naming_source = (validated_data.pop("naming_source", None) or "").strip() or None
channel = validated_data.get("channel")
if (
channel is not None
@@ -5389,7 +5392,7 @@ def create_task(
description = (validated_data.get("description") or "").strip()
update_fields: list[str] = []
if description and not (warm_task.title or "").strip():
- warm_task.title = generate_task_title(description)
+ warm_task.title = generate_task_title(naming_source or description)
warm_task.title_manually_set = False
update_fields += ["title", "title_manually_set"]
if description and not (warm_task.description or "").strip():
@@ -5476,8 +5479,8 @@ def create_task(
validated_data["github_user_integration"] = github_user_integration.integration
title = (validated_data.get("title") or "").strip()
- if not title and validated_data.get("description"):
- validated_data["title"] = generate_task_title(validated_data["description"])
+ if not title and (naming_source or validated_data.get("description")):
+ validated_data["title"] = generate_task_title(naming_source or validated_data["description"])
validated_data.setdefault("title_manually_set", False)
elif title:
validated_data.setdefault("title_manually_set", True)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 392b7980a99b..5efb70ee1e12 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -848,6 +848,17 @@ class TaskWriteSerializer(serializers.Serializer):
class TaskCreateSerializer(TaskWriteSerializer):
+ naming_source = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ write_only=True,
+ help_text=(
+ "Text the server generates the title from instead of `description`. Lets a client whose "
+ "`description` is only an attachment summary (e.g. pasted text stored as a file) supply the "
+ "real content for naming, so `description` (the prompt passed to the agent) stays unchanged. "
+ "Not persisted."
+ ),
+ )
sandbox_environment_id = serializers.UUIDField(
required=False,
default=None,
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index e4e35050fd31..86ef06481af9 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -905,6 +905,42 @@ class TestFacadeReadsAndMappers(TestCase):
assert created.latest_run is not None
self.assertEqual(created.latest_run.task_id, created.task_id)
+ @patch("products.tasks.backend.logic.services.title_generator.generate_task_title")
+ def test_create_task_names_from_naming_source_keeping_description_bare(self, mock_title):
+ # When a client pastes text (stored as an attachment), it sends the pasted content as
+ # naming_source so the title reads well, while description stays the bare prompt the
+ # agent — and the reload transcript dedup — expect.
+ mock_title.side_effect = lambda text: f"title:{text}"
+ dto = facade.create_task(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ validated_data={
+ "description": "Attached files: pasted-text.txt",
+ "naming_source": "Deploy blocks on a stale lockfile",
+ "origin_product": Task.OriginProduct.USER_CREATED,
+ },
+ )
+ task = Task.objects.get(id=dto.id)
+ self.assertEqual(task.description, "Attached files: pasted-text.txt")
+ self.assertEqual(task.title, "title:Deploy blocks on a stale lockfile")
+ self.assertFalse(task.title_manually_set)
+ mock_title.assert_called_once_with("Deploy blocks on a stale lockfile")
+
+ @patch("products.tasks.backend.logic.services.title_generator.generate_task_title")
+ def test_create_task_falls_back_to_description_without_naming_source(self, mock_title):
+ mock_title.side_effect = lambda text: f"title:{text}"
+ dto = facade.create_task(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ validated_data={
+ "description": "Fix the login redirect",
+ "origin_product": Task.OriginProduct.USER_CREATED,
+ },
+ )
+ task = Task.objects.get(id=dto.id)
+ self.assertEqual(task.title, "title:Fix the login redirect")
+ mock_title.assert_called_once_with("Fix the login redirect")
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_and_run_persists_dispatch_params_for_reconcile(self, _mock_workflow):
# The reconciler re-dispatches lost runs from the row alone, so the dispatch params
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index dea727911a1e..18a88437303b 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1818,6 +1818,8 @@ export interface TaskCreateApi {
* @nullable
*/
channel?: string | null
+ /** Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted. */
+ naming_source?: string
/**
* Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.
* @nullable
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index c44ceb5527fc..62e9fc98b5b8 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1196,6 +1196,12 @@ export const TasksCreateBody = /* @__PURE__ */ zod
"When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."
),
channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
+ naming_source: zod
+ .string()
+ .optional()
+ .describe(
+ 'Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted.'
+ ),
sandbox_environment_id: zod
.uuid()
.nullish()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9cd04248a134..3b0cc52b8138 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -80176,6 +80176,8 @@ export namespace Schemas {
* @nullable
*/
channel?: string | null;
+ /** Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted. */
+ naming_source?: string;
/**
* Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.
* @nullable
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 1819a43b9cb1..2f174cba806a 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -1115,6 +1115,12 @@ export const TasksCreateBody = /* @__PURE__ */ zod
"When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."
),
channel: zod.string().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
+ naming_source: zod
+ .string()
+ .optional()
+ .describe(
+ 'Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted.'
+ ),
sandbox_environment_id: zod
.string()
.nullish()
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index fc7a44c91355..525452dabb51 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -467,6 +467,7 @@ const TasksCreateSchema = TasksCreateBody.omit({
pending_user_artifact_ids: true,
auto_publish: true,
channel: true,
+ naming_source: true,
sandbox_environment_id: true,
custom_image_id: true,
runtime: true,