Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { localDb } from "main/lib/local-db";
import { workspaceInitManager } from "main/lib/workspace-init-manager";
import { z } from "zod";
import { publicProcedure, router } from "../../..";
import { generateWorkspaceNameFromPrompt } from "../utils/ai-name";
import { attemptWorkspaceAutoRenameFromPrompt } from "../utils/ai-name";
import { resolveWorkspaceBaseBranch } from "../utils/base-branch";
import { setBranchBaseConfig } from "../utils/base-branch-config";
import {
Expand Down Expand Up @@ -290,6 +290,7 @@ export const createCreateProcedures = () => {
z.object({
projectId: z.string(),
name: z.string().optional(),
prompt: z.string().optional(),
branchName: z.string().optional(),
baseBranch: z.string().optional(),
useExistingBranch: z.boolean().optional(),
Expand Down Expand Up @@ -411,6 +412,24 @@ export const createCreateProcedures = () => {
branch,
name: input.name ?? branch,
});
let autoRenameWarning: string | undefined;
try {
const autoRenameResult =
await attemptWorkspaceAutoRenameFromPrompt({
workspaceId: workspace.id,
prompt: input.prompt,
});
autoRenameWarning =
autoRenameResult.status === "skipped"
? autoRenameResult.warning
: undefined;
} catch (error) {
console.warn("[workspaces/create] Auto naming failed", {
workspaceId: workspace.id,
error: error instanceof Error ? error.message : String(error),
});
autoRenameWarning = "Couldn't auto-name this workspace.";
}
activateProject(project);
const setupConfig = loadSetupConfig({
mainRepoPath: project.mainRepoPath,
Expand All @@ -423,6 +442,7 @@ export const createCreateProcedures = () => {
worktreePath: orphanedWorktree.path,
projectId: project.id,
isInitializing: false,
autoRenameWarning,
wasExisting: true,
};
}
Expand Down Expand Up @@ -491,6 +511,7 @@ export const createCreateProcedures = () => {
worktreePath,
branch,
mainRepoPath: project.mainRepoPath,
namingPrompt: input.prompt,
useExistingBranch: input.useExistingBranch,
});

Expand Down Expand Up @@ -952,14 +973,6 @@ export const createCreateProcedures = () => {
workspaceName,
});
}),

generateName: publicProcedure
.input(z.object({ prompt: z.string().min(1) }))
.mutation(async ({ input }) => {
const name = await generateWorkspaceNameFromPrompt(input.prompt);
return { name };
}),

importAllWorktrees: publicProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input }) => {
Expand Down
179 changes: 144 additions & 35 deletions apps/desktop/src/lib/trpc/routers/workspaces/utils/ai-name.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1,86 @@
import { createAnthropic } from "@ai-sdk/anthropic";
import { createOpenAI } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import type { Agent } from "@mastra/core/agent";
import {
generateTitleFromMessage,
getCredentialsFromAnySource as getAnthropicCredentialsFromAnySource,
getAnthropicProviderOptions,
getOpenAICredentialsFromAnySource,
} from "@superset/chat/host";
import { workspaces } from "@superset/local-db";
import { and, eq, isNull } from "drizzle-orm";
import { localDb } from "main/lib/local-db";
import { getWorkspaceAutoRenameDecision } from "./workspace-auto-rename";

export type WorkspaceAutoRenameResult =
| { status: "renamed"; name: string }
| {
status: "skipped";
reason:
| "empty-prompt"
| "missing-credentials"
| "generation-failed"
| "missing-workspace"
| "empty-generated-name"
| "workspace-deleting"
| "workspace-named"
| "workspace-name-changed";
warning?: string;
};

type AgentModel = ConstructorParameters<typeof Agent>[0]["model"];
type AnthropicCredentials = NonNullable<
ReturnType<typeof getAnthropicCredentialsFromAnySource>
>;
type OpenAICredentials = NonNullable<
ReturnType<typeof getOpenAICredentialsFromAnySource>
>;

interface TitleProvider {
name: "Anthropic" | "OpenAI";
agentId: string;
resolveApiKey: () => string | null;
createModel: (apiKey: string) => AgentModel;
resolveCredentials: () => AnthropicCredentials | OpenAICredentials | null;
createModel: (
credentials: AnthropicCredentials | OpenAICredentials,
) => AgentModel;
}

const TITLE_PROVIDERS: TitleProvider[] = [
{
name: "Anthropic",
agentId: "workspace-namer-anthropic",
resolveApiKey: () => getAnthropicCredentialsFromAnySource()?.apiKey ?? null,
createModel: (apiKey) =>
createAnthropic({ apiKey })("claude-haiku-4-5-20251001"),
resolveCredentials: () => getAnthropicCredentialsFromAnySource(),
createModel: (credentials) =>
createAnthropic(getAnthropicProviderOptions(credentials))(
"claude-haiku-4-5-20251001",
),
},
{
name: "OpenAI",
agentId: "workspace-namer-openai",
resolveApiKey: () => getOpenAICredentialsFromAnySource()?.apiKey ?? null,
createModel: (apiKey) => createOpenAI({ apiKey })("gpt-4o-mini"),
resolveCredentials: () => getOpenAICredentialsFromAnySource(),
createModel: (credentials) =>
createOpenAI({ apiKey: credentials.apiKey })("gpt-4o-mini"),
},
];

async function generateTitleWithModel(
prompt: string,
agentId: string,
model: AgentModel,
): Promise<string | null> {
const agent = new Agent({
id: agentId,
name: "Workspace Namer",
instructions: "You generate concise workspace titles.",
model,
});

const title = await agent.generateTitleFromUserMessage({
message: prompt,
tracingContext: {},
});

return title?.trim() || null;
}

export async function generateWorkspaceNameFromPrompt(
prompt: string,
): Promise<string | null> {
for (const provider of TITLE_PROVIDERS) {
const apiKey = provider.resolveApiKey();
if (!apiKey) {
const credentials = provider.resolveCredentials();
if (!credentials) {
continue;
}

try {
const title = await generateTitleWithModel(
prompt,
provider.agentId,
provider.createModel(apiKey),
);
const title = await generateTitleFromMessage({
message: prompt,
agentModel: provider.createModel(credentials),
agentId: provider.agentId,
agentName: "Workspace Namer",
instructions: "You generate concise workspace titles.",
});
if (title) {
return title;
}
Expand All @@ -79,3 +94,97 @@ export async function generateWorkspaceNameFromPrompt(

return null;
}

export async function attemptWorkspaceAutoRenameFromPrompt({
workspaceId,
prompt,
}: {
workspaceId: string;
prompt?: string | null;
}): Promise<WorkspaceAutoRenameResult> {
const cleanedPrompt = prompt?.trim();
if (!cleanedPrompt) {
return { status: "skipped", reason: "empty-prompt" };
}

const generatedName = await generateWorkspaceNameFromPrompt(cleanedPrompt);
if (!generatedName) {
const hasCredentials =
getAnthropicCredentialsFromAnySource() !== null ||
getOpenAICredentialsFromAnySource() !== null;
return {
status: "skipped",
reason: hasCredentials ? "generation-failed" : "missing-credentials",
warning: hasCredentials
? "Couldn't auto-name this workspace."
: "Couldn't auto-name this workspace because chat credentials aren't configured.",
};
}

const workspace = localDb
.select({
id: workspaces.id,
branch: workspaces.branch,
name: workspaces.name,
isUnnamed: workspaces.isUnnamed,
deletingAt: workspaces.deletingAt,
})
.from(workspaces)
.where(eq(workspaces.id, workspaceId))
.get();

const decision = getWorkspaceAutoRenameDecision({
workspace: workspace ?? null,
generatedName,
});
if (decision.kind === "skip") {
return { status: "skipped", reason: decision.reason };
Comment on lines +110 to +141
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Short-circuit skip cases before generating a title.

attemptWorkspaceAutoRenameFromPrompt() calls the provider before loading the workspace. If the workspace is already missing, deleting, or no longer eligible for rename, this still burns a provider call and can return missing-credentials / generation-failed instead of the real skip reason. Load the workspace first, return the non-empty-generated-name skip cases early, then keep the guarded UPDATE as the post-generation race check.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/lib/trpc/routers/workspaces/utils/ai-name.ts` around lines
115 - 146, The function attemptWorkspaceAutoRenameFromPrompt currently calls
generateWorkspaceNameFromPrompt before loading the workspace, which can consume
provider calls and return wrong skip reasons; move the localDb select that loads
the workspace (using workspaceId and localDb/select/from/where) to run before
generateWorkspaceNameFromPrompt, run getWorkspaceAutoRenameDecision on the
loaded workspace to short-circuit and return non-"empty-generated-name" skip
cases early, and only call generateWorkspaceNameFromPrompt and the guarded
UPDATE if the decision allows renaming, keeping the existing post-generation
race check that uses generatedName and getWorkspaceAutoRenameDecision.

}
if (!workspace) {
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This if (!workspace) block is unreachable because getWorkspaceAutoRenameDecision already returns kind: "skip" when workspace is null. After the skip return, workspace must be non-null, so this block is dead code. Remove it to avoid misleading control flow.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/lib/trpc/routers/workspaces/utils/ai-name.ts, line 148:

<comment>This `if (!workspace)` block is unreachable because `getWorkspaceAutoRenameDecision` already returns `kind: "skip"` when workspace is null. After the skip return, workspace must be non-null, so this block is dead code. Remove it to avoid misleading control flow.</comment>

<file context>
@@ -128,32 +128,68 @@ export async function attemptWorkspaceAutoRenameFromPrompt({
+	if (decision.kind === "skip") {
 		return { status: "skipped", reason: decision.reason };
 	}
+	if (!workspace) {
+		return { status: "skipped", reason: "missing-workspace" };
+	}
</file context>
Fix with Cubic

return { status: "skipped", reason: "missing-workspace" };
}

const renameResult = localDb
.update(workspaces)
.set({
name: decision.name,
isUnnamed: false,
updatedAt: Date.now(),
})
.where(
and(
eq(workspaces.id, workspace.id),
eq(workspaces.branch, workspace.branch),
eq(workspaces.name, workspace.branch),
eq(workspaces.isUnnamed, true),
isNull(workspaces.deletingAt),
),
)
.run();
Comment thread
Kitenite marked this conversation as resolved.
if (renameResult.changes > 0) {
return { status: "renamed", name: decision.name };
}

const latestWorkspace = localDb
.select({
branch: workspaces.branch,
name: workspaces.name,
isUnnamed: workspaces.isUnnamed,
deletingAt: workspaces.deletingAt,
})
.from(workspaces)
.where(eq(workspaces.id, workspace.id))
.get();

const latestDecision = getWorkspaceAutoRenameDecision({
workspace: latestWorkspace ?? null,
generatedName,
});
return {
status: "skipped",
reason:
latestDecision.kind === "skip"
? latestDecision.reason
: "workspace-name-changed",
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, expect, test } from "bun:test";
import {
getWorkspaceAutoRenameDecision,
resolveWorkspaceAutoRename,
} from "./workspace-auto-rename";

describe("resolveWorkspaceAutoRename", () => {
test("returns generated name for untouched unnamed workspace", () => {
expect(
resolveWorkspaceAutoRename({
workspace: {
branch: "feat/test-branch",
name: "feat/test-branch",
isUnnamed: true,
deletingAt: null,
},
generatedName: "Fix auth flow",
}),
).toBe("Fix auth flow");
});

test("does not overwrite an already named workspace", () => {
expect(
resolveWorkspaceAutoRename({
workspace: {
branch: "feat/test-branch",
name: "Custom name",
isUnnamed: false,
deletingAt: null,
},
generatedName: "Fix auth flow",
}),
).toBeNull();
});

test("does not overwrite placeholder once another name has been applied", () => {
expect(
resolveWorkspaceAutoRename({
workspace: {
branch: "feat/test-branch",
name: "Running setup",
isUnnamed: true,
deletingAt: null,
},
generatedName: "Fix auth flow",
}),
).toBeNull();
});

test("ignores empty generated names", () => {
expect(
resolveWorkspaceAutoRename({
workspace: {
branch: "feat/test-branch",
name: "feat/test-branch",
isUnnamed: true,
deletingAt: null,
},
generatedName: " ",
}),
).toBeNull();
});

test("reports skip reason for already named workspace", () => {
expect(
getWorkspaceAutoRenameDecision({
workspace: {
branch: "feat/test-branch",
name: "Custom name",
isUnnamed: false,
deletingAt: null,
},
generatedName: "Fix auth flow",
}),
).toEqual({
kind: "skip",
reason: "workspace-named",
});
});
});
Loading
Loading